コンポーネント 子→親

emit

by sarunokoshikake

HTML

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

JavaScript

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')
    }
  },
});

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