猿问

vue两个不同子组件的$ref为何却指向同一个方法?

https://img3.mukewang.com/5c80bbf00001b33303370247.jpg

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

绝地无双
浏览 755回答 1
1回答

哈士奇WWW

有没有尝试用Bus呢?用法如下//假设 bb 组件里面有个按钮,点击按钮,把 123 传递给 aa 组件// 根组件(this.$root)new Vue({&nbsp;el: '#app',&nbsp;router,&nbsp;render: h => h(App),&nbsp;data: {&nbsp; // 空的实例放到根组件下,所有的子组件都能调用&nbsp; Bus: new Vue()&nbsp;}})bb 组件内调用事件触发↓<button @click="submit">提交<button>methods: {&nbsp; submit() {&nbsp; &nbsp;// 事件名字自定义,用不同的名字区别事件&nbsp; &nbsp;this.$root.Bus.$emit('eventName', 123)&nbsp; }&nbsp;}aa 组件内调用事件接收↓&nbsp;// 当前实例创建完成就监听这个事件&nbsp;created(){&nbsp; this.$root.Bus.$on('eventName', value => {&nbsp; &nbsp;this.print(value)&nbsp; })&nbsp;},&nbsp;methods: {&nbsp; print(value) {&nbsp; &nbsp;console.log(value)&nbsp; }&nbsp;},&nbsp;// 在组件销毁时别忘了解除事件绑定&nbsp;beforeDestroy() {&nbsp; &nbsp;this.$root.Bus.$off('eventName')&nbsp;},
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答