Vueで親コンポーネントへdataの値を渡す方法

Vueで親コンポーネントへdataの値を渡す方法について備忘録としてこちらにまとめます。

Vueのインスタンスをグローバル登録した際にdataプロパティの値を親コンポーネントに渡す方法は、以下の2つになります。

1つ目

  <div id="app">
    <my-component v-bind:list="list"></my-component>
  </div>
Vue.component('my-component', {
  template: `
    <ul>
      <comp-child v-for="item in list" v-bind:key="item.id" v-bind:name="item.name" v-bind:hp="item.hp"></comp-child>
    </ul>`,
    props: ['list']
})

Vue.component('comp-child', {
  template: '<li>{{ name }} HP.{{ hp }}</li>',
  props: ['name', 'hp']
});

new Vue({
  el: '#app',
  data: {
    list: [
      { id: 1, name: 'スライム', hp: 100 },
      { id: 2, name: 'ゴブリン', hp: 200 },
      { id: 3, name: 'ドラゴン', hp: 500 }
    ]
  }
});

Vueインスタンスにdataプロパティが設定されているので、htmlのid="app"の中では、dataの値を使えるので、v-bindで属性を設定し、属性の値としてdataの値を渡す。
親コンポーネント(my-component)でpropsとして属性に設定した値を受け取る。

2つ目

  <div id="app">
  </div>
Vue.component('my-component', {
  template: `
    <ul>
      <comp-child v-for="item in list" v-bind:key="item.id" v-bind:name="item.name" v-bind:hp="item.hp"></comp-child>
    </ul>`,
    props: ['list']
})

Vue.component('comp-child', {
  template: '<li>{{ name }} HP.{{ hp }}</li>',
  props: ['name', 'hp']
});

new Vue({
  el: '#app',
  data: {
    list: [
      { id: 1, name: 'スライム', hp: 100 },
      { id: 2, name: 'ゴブリン', hp: 200 },
      { id: 3, name: 'ドラゴン', hp: 500 }
    ]
  },
  template: '<my-component :list="list"></my-component>'
});

template オプションを使って、my-component をルートコンポーネントとして指定する。

※ ルートコンポーネントとは、Vue.jsアプリケーション全体のエントリーポイントとなる最初のコンポーネントのことを指します。
このルートコンポーネントが、他のすべての子コンポーネントの親となる。
一般的には、Vueインスタンスに直接マウントされるコンポーネントのことを指す。
id="app"の部分にルートコンポーネントがマウントされる。