我的需求是:在父组件里同时调用两个不同子组件的方法!我用ref只能顺利调用一个子组件的方法,两个或多个的时候 ref就会被覆盖
1 回答

哈士奇WWW
TA贡献1799条经验 获得超6个赞
有没有尝试用Bus呢?
用法如下
//假设 bb 组件里面有个按钮,点击按钮,把 123 传递给 aa 组件
// 根组件(this.$root)
new Vue({
el: '#app',
router,
render: h => h(App),
data: {
// 空的实例放到根组件下,所有的子组件都能调用
Bus: new Vue()
}
})
bb 组件内调用事件触发↓
<button @click="submit">提交<button>
methods: {
submit() {
// 事件名字自定义,用不同的名字区别事件
this.$root.Bus.$emit('eventName', 123)
}
}
aa 组件内调用事件接收↓
// 当前实例创建完成就监听这个事件
created(){
this.$root.Bus.$on('eventName', value => {
this.print(value)
})
},
methods: {
print(value) {
console.log(value)
}
},
// 在组件销毁时别忘了解除事件绑定
beforeDestroy() {
this.$root.Bus.$off('eventName')
},
添加回答
举报
0/150
提交
取消