Vue-自定义事件

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

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

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

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

注意:

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

例子:

<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="incrementCounter">{{counter}}</button>',
    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的监听器。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容