Vue-自定义事件

在父组件使用prop 传递数据给子组件,子组件则是通过事件传递数据给父组件的。

Vue实例都会实现事件接口:

1.使用$on(eventName)监听事件;
2.使用$emit(eventName,optionalPayload)触发事件;

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

注意:

不能用$on来监听子组件释放的事件,而是必须在模板里直接用v-on绑定。

例子:

{{total}}

Vue.component('button-counter',{ template:'', data:function() { return { counter:0 } }, methods:{ incrementCounter:function() { this.counter+=1 this.$emit('increment') } } }) new Vue({ el:'#counter-event-example', data:{ total:0 }, methods:{ incrementTotal:function(){ this.total+=1 } } })

目的

这样子的代码使得父组件与子组件进行了解耦,让数据在各自的作用域内进行操作。


.sync 修饰符

.sync 修饰符功能在2.3版本之后,作为一个编译时的一个语法糖,它会被拓展为一个自动更新的父组件属性的v-on的监听器。

你可能感兴趣的:(Vue-自定义事件)