vue2.0中v-on绑定自定义事件的理解

Posted return00

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue2.0中v-on绑定自定义事件的理解相关的知识,希望对你有一定的参考价值。

vue中父组件通过prop传递数据给子组件,而想要将子组件的数据传递给父组件,则可以通过自定义事件的绑定。

每个Vue实例都实现了【事件接口】,即:

1、使用 $on(eventName) 监听事件

2、使用 $emit(eventName) 触发事件

父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。

html代码:

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

css代码:

 1 Vue.component(‘button-counter‘, {
 2   template: ‘<button v-on:click="increment">{{ counter }}</button>‘,
 3   data: function () {
 4     return {
 5       counter: 0
 6     }
 7   },
 8   methods: {
 9     increment: function () {
10       this.counter += 1
11       this.$emit(‘increment‘)
12     }
13   },
14 })
15 new Vue({
16   el: ‘#counter-event-example‘,
17   data: {
18     total: 0
19   },
20   methods: {
21     incrementTotal: function () {
22       this.total += 1
23     }
24   }
25 })

 

在子组件里面把点击事件(click)绑定给了函数increment。点击子组件的按钮将会触发位于子组件的increment函数。

this.$emit(‘increment‘这是触发当前实例上的事件。附加参数都会传给监听器回调。

子组件在调用了increment函数的时候,通过$emit来通知父组件。这样就形成父子组件间的相互呼应传递信息。

在平常的组件通讯,父组件是通过props参数对子组件进行传递,而子组件向父组件传递则可以使用自定义事件了。

这样,父组件和子组件已经解耦,子组件收到的是父组件内部的实现

 
 

以上是关于vue2.0中v-on绑定自定义事件的理解的主要内容,如果未能解决你的问题,请参考以下文章

Vue组件绑定自定义事件

vue2.0那些坑之使用elementUI后v-on:click事件不生效问题

Vue2.0学习—组件的自定义事件(五十八)

Vue.js 绑定到名称中带有点的 DOM 自定义事件(如引导事件)

Vue2.0学习—事件处理和事件修饰符(三十二)

如何在 Vue 中使用 v-bind 和 v-on 绑定自定义命名模型?