1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Vue.js]子から親へ

Last updated at Posted at 2021-08-05

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

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

1
1
2

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?