vue 的自定義事件


vue的自定義事件非常有趣,大意為子組件使用了一個事件,比如click然后產生了一個效果,這樣的效果便可以為自定義事件了。然后將這樣的效果命名放入父組件中,當做一個事件來觸發,每當這樣的效果發生一次時,這樣父組件的事件也被觸發了,即可以產生另一種效果,這樣可以加強這兩個效果的緊密聯系,並且這樣有趣又好用的方式也可以用在自己想要的地方。自定義事件的強大算是初步體會到了。

例子:

<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>


Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})


new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM