Vue-自定义事件

作者: bouble | 来源:发表于2018-04-03 18:15 被阅读38次

在父组件使用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的监听器。

相关文章

  • Vue-自定义事件

    在父组件使用prop 传递数据给子组件,子组件则是通过事件传递数据给父组件的。 Vue实例都会实现事件接口: 1....

  • vue-事件

    title: vue-事件处理date: 2017-03-23 vue 事件 本文介绍vue组件的事件处理,并通过...

  • 前端框架:Vue-自定义事件

    有时候,我们希望触发父组件的某个事件时,可以通知到子组件;触发子组件的某个事件时,可以通知到父组件。 Vue实例实...

  • Vue-(4)表单-组件-自定义事件

    一:表单 v-model 会根据控件类型自动选取正确的方法来更新元素 运行结果: QQ20210817-14245...

  • Vue-表单事件

    1. 效果图 2. 实现代码 css html 用到的属性:v-model , .trim , .number ,...

  • Vue-键盘事件

  • vue-事件总线

    VueComponent.prototype.proto === Vue.prototype 利用这个关系 mai...

  • 自定义事件js

    title: 自定义事件date: 2017-06-06 15:36:04tags: 自定义事件 js的自定义事件...

  • jQuery例子记录(持续更新)

    目录: 1.自定义事件2.操作DOM(与JS原生对比) 1.自定义事件 绑定自定义事件: 事件名称refresh....

  • JavaScript之事件完整篇

    目录html原生事件自定义事件node中的自定义事件前端框架的自定义事件 一、html原生事件 1. 概念 观察者...

网友评论

    本文标题:Vue-自定义事件

    本文链接:https://www.haomeiwen.com/subject/xsechftx.html