data () {
return {
title: 'Vue.js'
}
},
methods: {
sayHello () {
window.alert('Hello');
}
}
}
// 父组件
<template>
<component-a ref="comA"></component-a>
</template>
<script>
export default {
mounted () {
const comA = this.$refs.comA;
console.log(comA.title); // Vue.js
comA.sayHello(); // 弹窗
}
}
</script>
不过, 这两种方法的弊端是,无法在跨级或兄弟间通信 。
// parent.vue
<component-a></component-a>
<component-b></component-b>
<component-b></component-b>我们想在 component-a 中,访问到引用它的页面中(这里就是 parent.vue)的两个 component-b 组件,那这种情况下,就得配置额外的插件或工具了,比如 Vuex 和 Bus 的解决方案。
总结
常见使用场景可以分为三类:
父子通信: 父向子传递数据是通过 props,子向父是通过 events( $emit );通过父链 / 子链也可以通信( $parent / $children );ref 也可以访问组件实例;provide / inject API。
兄弟通信: Bus;Vuex;
跨级通信: Bus;Vuex;provide / inject API、 $attrs/$listeners
以上所述是小编给大家介绍的vue组件间通信六种方式(总结篇),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对软件开发网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!










