javascript - vue中的自定义事件只能子传父?

查看:65
本文介绍了javascript - vue中的自定义事件只能子传父?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我想通过父组件中的this.$emit的方法来触发子组件中的this.$on,应该要怎么做?
我做过的尝试:
使用vue2.x

style:

#parent {
        width: 200px;
        height: 200px;
        background-color: #eee;
    }
    
.child {
    width: 100px;
    height: 100px;
    background-color: red;
}

html:

<div id="parent" @click="test">
    <p>{{ total }}</p>
    <child v-on:increment="test"></child>
</div>

javascript:

Vue.component('child', {
    template: '<div class="child" @click.stop="add">{{ counter }}</div>',
    created: function() {
        //子组件初始化时监听'increment'事件
        this.$on('increment', function() {
            this.counter += 1;
        });
    },
    data: function() {
        return {
            counter: 0
        }
    },
    methods: {
        add: function() {
            //子组件中点击后执行,触发自身increment事件
            this.$emit('increment');
        }
    },
})
new Vue({
    el: '#parent',
    data: {
        total: 0
    },
    methods: {
        test: function() {
         //父组件中点击后执行,不触发子组件的increment事件
            this.total += 1;
            this.$emit('increment');
        }
    }
})

解决方案

通过ref match到子组件 直接调用子组件的method

或者 https://vuefe.cn/guide/migrat...

这篇关于javascript - vue中的自定义事件只能子传父?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆