検索

ホームページ  >  に質問  >  本文

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:

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

javascript:

Vue.component('child', {
    template: '<p class="child" @click.stop="add">{{ counter }}</p>',
    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');
        }
    }
})
PHPzPHPz2896日前209

全員に返信(3)返信します

  • ringa_lee

    ringa_lee2017-04-10 17:31:25

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

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

    返事
    0
  • 迷茫

    迷茫2017-04-10 17:31:25

    确实无法使用父组件触发子组件的事件,但是可以使用props代替。
    在子组件监听传值,传值改变则触发事件。

    返事
    0
  • 天蓬老师

    天蓬老师2017-04-10 17:31:25

    组件是为了解耦。也就是说,父组件中可能没有子组件,这个时候怎么传。
    不过,可以采用其他方式实现:比如通过props来通知子组件,父组件的变化。

    返事
    0
  • キャンセル返事