我想通过父组件中的this.$emit的方法来触发子组件中的this.$on,应该要怎么做?
我做过的尝试:
使用vue2.x
#parent {
width: 200px;
height: 200px;
background-color: #eee;
}
.child {
width: 100px;
height: 100px;
background-color: red;
}
<p id="parent" @click="test">
<p>{{ total }}</p>
<child v-on:increment="test"></child>
</p>
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');
}
}
})
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
通过ref match到子组件 直接调用子组件的method
或者 https://vuefe.cn/guide/migrat...
确实无法使用父组件触发子组件的事件,但是可以使用props代替。
在子组件监听传值,传值改变则触发事件。
组件是为了解耦。也就是说,父组件中可能没有子组件,这个时候怎么传。
不过,可以采用其他方式实现:比如通过props来通知子组件,父组件的变化。