[Vue.js]子から親へ


HTML

<div id="fruits-counter">
  <div v-for="fruit in fruits">
    {{fruit.name}}: <counter-button v-on:increment="incrementCartStatus()"></counter-button>
  </div>
  <p>合計: {{total}}</p>
</div>

Vue.js[子]

var counterButton = Vue.extend({
  template: '<span>{{counter}}個<button v-on:click="addToCart">追加</button></span>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    addToCart: function () {
      this.counter += 1
      this.$emit('increment') // incrementカスタムイベントの発火
    }
  },
})

Vue.js[親]

new Vue({
  el: '#fruits-counter',
  components:{
    'counter-button': counterButton
  },
  data: {
    total: 0,
    fruits: [
      {name: ''},
      {name: 'イチゴ'}
    ]
  },
  methods: {
    incrementCartStatus: function () {
      this.total += 1
    }
  }
})

動作の流れ

①「子」addcart関数動作
②「子」自身のcounterに+1
③$emitにより「親」incrementカスタムイベント発火
④incrementCartStatus関数動作
⑤「親」totalに+1

親から子よりずいぶんわかりずらい、、、