Vue - 自定义事件

原文链接: http://www.cnblogs.com/xiaobaiv/p/9158352.html

$emit

我们知道,父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,应该怎样做?那就是自定义事件!

使用 v-on 监听事件
使用 $emit 触发事件
$emit(事件名,传递的数据)

<div id="app">
    <p>{{todo}}</p>
    <mycomponent @inset="adds"></mycomponent>
    <mycomponent @inset="adds"></mycomponent>
</div>
<script>  
var componentA = {
    data: function(){
        return{
            count: 0
        }
    },
    template: '<button @click="add" type="button">{{count}}</button>',
    methods: {
        add: function(){
            this.count++;
            // 触发自定义事件
            this.$emit('inset', this.count)
        }
    }
}
new Vue({
    el: '#app',
    data: {
        todo: 0
    },
    components: {
        // 引用组件
        'mycomponent': componentA
    },
    methods: {
        adds: function(num){
            this.todo++;
            console.log(num)
        }
    }
})
</script>

1321525-20180609073937975-458615023.gif

转载于:https://www.cnblogs.com/xiaobaiv/p/9158352.html

猜你喜欢

转载自blog.csdn.net/weixin_30781433/article/details/94796874