一、父子通信props
适用于父子组件的通信
子组件:Son.vue
...
<h2>子组件</h2>
<!-- 直接在html标签中,自定义sonClick事件,并向传递arg参数 -->
<button @click="$emit('sonClick','arg')">子组件按钮</button>
...
-------另一种写法------
...
<h2>子组件</h2>
<!-- 监听点击,在methods中处理 -->
<button @click="toFather">子组件按钮</button>
...
<script>
export default {
name: "GrandSon",
methods: {
toFather() {
// 自定义sonClick事件,并向传递参数'arg'
this.$emit("sonClick", "arg");
},
},
};
</script>
父组件:Father.vue
...
<h2>父组件</h2>
<!-- 监听子组件的自定义事件,并在sonClick方法中处理 -->
<Son @sonClick="handleSonClick" />
...
<script>
import Son from "./Son.vue";
export default {
components: { Son },
name: "Father",
methods: {
handleSonClick(arg) {
console.log(arg); //arg
},
},
};
</script>
二、祖孙通信
适用于祖孙之间的通信
孙子组件:GrandSon.vue
...
<h2>孙子组件</h2>
<!-- 监听点击,自定义grandSonClick,并传递arg参数 -->
<button @click="$emit('grandSonClick','arg')">孙子组件按钮</button>
...
儿子组件:Son.vue
...
<h2>父组件</h2>
<!-- 获取父组件的自定义事件,并向下监听,这样爷爷组件就可以监听到孙子组件的事件-->
<grand-son v-on="$listeners" />
等同于:
<grand-son @grandSonClick="$emit('grandSonClick',arg)" />
...
爷爷组件:GrandFather.vue
...
<h2>爷爷组件</h2>
<!-- 监听孙子组件的自定义事件,并处理 -->
<Son @grandSonClick="handler"/>
...
<script>
import Son from './Son.vue'
export default {
components: { Son },
name: 'GrandFather',
methods:{
handler(arg){
console.log(arg) //arg
}
}
}
</script>
三、$bus事件总线
适用于层级复杂,兄弟组件之间的通信
项目入口文件:main.js
...
new Vue({
render: h => h(App),
beforeCreate(){
Vue.prototype.$bus=this //在beforeCreate时,vue原型链上添加$bus,$bus等于vue实例,可以使用vue实例的所有方法,包括$emit与on
}
}).$mount('#app')
/*---另一种写法---*/
Vue.prototype.$bus = new Vue()
new Vue({
render: h => h(App),
}).$mount('#app')
组件1:one.vue
...
<h2>组件1</h2>
<!-- 监听点击,在methods中处理 -->
<button @click="oneClick">子组件按钮</button>
...
<script>
export default {
...
methods: {
oneClick() {
this.$bus.$emit('userClick','arg')
},
}
</script>
组件2:two.vue
...
// 挂载的时候,监听$bus的事件,参数1:事件名,参数2:回调函数
mounted(){
this.$bus.$on("userClick",(arg)=>{
console.log(arg) //arg
})
}