LoginSignup
5
7

More than 5 years have passed since last update.

VueのComponentにObjectを渡したいのに属性値だよ消えるよって怒られる

Posted at

webpackerを使ってVueJSを書いている中で、
componentへObjectを継承したい場面でぶつかった壁の話。

なんも考えずにやると、

// parent.vue
<template>
  <child hoge="hoge">
</template>

<script>
import Child from 'child'

export default {
  components: {
    'child': Child
  },
  data () {
    return {
      hoge: {
        name: 'hoge',
        age: 30
      }
    }
  }
}
</script>


// child.vue
<template>
  <p v-text="hoge.name"></p>
</template>

<script>
export default {
  props: ['hoge']
}
</script>

みたいな感じで、子のコンポーネントのprops値としてオブジェクト渡せるかなーと思ったんですが、
このような書き方だと、子のprops値 hoge には、Stringとして'hoge' が入ってきてしまいました。

別のやり方を探って

この辺を見て、親コンポーネントで

<child hoge="{{hoge}}">

とかやってみると

Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of...

というようなコンパイルエラーが出てしまいました。

解決策

結論をいうと

<child :hoge="hoge">

これでした。

<child :hoge="{{hoge}}">

とかやってもうまくいかずで、
http://qiita.com/satetsu888/items/abd67917097ee00d768d
こちらの記事の中で使っていた方法を試したらうまくいきました。

よく見たらエラー文言に書いてある通りなんですが、

hoge="hoge" → 通る
hoge="{{hoge}}" → 怒られる
:hoge="{{hoge}}" → 怒られる

という手順を踏んでしまったのでハマった感じですね。。
検索していてもドンピシャっぽい記事がなくて困ったので書いておきます。

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7