vue项目中,组件间的通信是最常用到的,也是面试必问的问题之一。
组件通信可以分为几种类型:
1、父子通信
1.1 父传子
1.2 子传父
2、跨级传递
2.1祖父传孙
3.1孙传祖父
3、同级组件间通信
首先说一下通用的方式,即不管哪种场景都在功能上可以实现,撇开具体场景的适合程度,其实也就是全局的通信方式。
一、vue bus 以vue实例为总线,传递数据
新建bus.js和busA.vue、busB.vue:
bus.js
import Vue from "vue"
const Bus = new Vue();
export default Bus;
在main.js引入,挂载到全局上去:
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import Bus from "@/utils/bus";
Vue.config.productionTip = false;
Vue.prototype.bus = Bus;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
busA.vue:
<template>
<div class="input">
<button @click="handleClick">click</button>
</div>
</template>
<script>
export default {
data() {
return {
};
},
methods: {
handleClick() {
this.bus.$emit("change", 12333) // 触发事件
}
}
};
</script>
<style>
.input{
display: flex;
}
</style>
busB.vue:
<template>
<div class="input">
</div>
</template>
<script>
export default {
data() {
return {
};
},
created() {
this.bus.$on('change', this.handleClick) // 监听事件
},
methods: {
handleClick(val) {
console.log(val)
}
}
};
</script>
&