軟件界面設(shè)計(jì)工具下載刷seo快速排名
?組件間通信方式是前端必不可少的知識點(diǎn),前端開發(fā)經(jīng)常會遇到組件間通信的情況,而且也是前端開發(fā)面試常問的知識點(diǎn)之一。接下來開始組件間通信方式第三彈------$bus,并講講分別在Vue2、Vue3中的表現(xiàn)。
Vue2+Vue3組件間通信方式匯總(1)------props
Vue2+Vue3組件間通信方式匯總(2)------$emit
一、全局總線$bus 原型鏈
歸根結(jié)底就是在vm,vue原型鏈上注冊一個(gè)名叫$bus 的對象,再把this,就是vm實(shí)例對象賦給$bus,其中$on $emit $off等就是全局可以讀可寫的變量,即可實(shí)現(xiàn),相關(guān)組件、不相關(guān)組件之間數(shù)組地傳遞。
------Vue2?
main.js文件中,Vue實(shí)例下,往Vue原型鏈上注冊屬性:$bus
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//關(guān)閉Vue的生產(chǎn)提示
Vue.config.productionTip = false//創(chuàng)建vm
new Vue({el:'#app',render: h => h(App),beforeCreate() {Vue.prototype.$bus = this//注冊全局事件總線}
})
其中一個(gè)組件:調(diào)用全局總線的$emit:
<template><div class="student"><h2>學(xué)生姓名:{{name}}</h2><h2>學(xué)生性別:{{sex}}</h2><button @click="sendStudentName">把學(xué)生名給另一個(gè)組件</button></div>
</template><script>export default {name:'Student',data() {return {name:'張三',sex:'男',}},methods:{sendStudentName(){this.$bus.$emit('hello',this.name)}}}
</script><style scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}
</style>
?另一個(gè)組件:調(diào)用全局總線的$on:
<template><div class="school"><h2>學(xué)校名稱:{{name}}</h2><h2>學(xué)校地址:{{address}}</h2></div>
</template><script>export default {name:'School',data() {return {name:'學(xué)校名',address:'學(xué)校地址',}},mounted() {this.$bus.$on('hello',(data) => { //綁定自定義事件hello,并留下回調(diào)函數(shù)console.log('我收到了'+data);})},beforeDestroy() {this.$bus.$off('hello') },}
</script><style scoped>.school{background-color: skyblue;padding: 5px;}
</style>
?------Vue3? ?不存在vm所以需要引入mitt插件
npm install mitt
在bus.ts文件中引入:?
import mitt from "mitt"
//mitt是一個(gè)函數(shù),賦給命名為$bus的變量
const $bus=mitt();
//向外暴露這個(gè)變量
export default $bus
?其中一個(gè)組件:
使用mitt中的$emit函數(shù),向$on傳輸數(shù)據(jù),第一個(gè)參數(shù)是和$on第一個(gè)參數(shù)向?qū)?yīng)的字段名,余下的參數(shù)是要傳輸?shù)臄?shù)據(jù),和Vue實(shí)例對象上的$emit,$on用法差不多.
<template><div class="student"><h2>學(xué)生姓名:{{name}}</h2><h2>學(xué)生性別:{{sex}}</h2><button @click="sendStudentName">把學(xué)生名給另一個(gè)組件</button></div>
</template><script setup lang="ts">
import ref from "vue"
import $bus from "./bus.ts"
let name=ref("張三")
let sex=ref("男")
let sendStudentName=(name.value)=>{
//使用mitt中的$emit函數(shù),向$on傳輸數(shù)據(jù),第一個(gè)參數(shù)是和$on第一個(gè)參數(shù)向?qū)?yīng)的字段名,余下的參數(shù)是要傳輸?shù)臄?shù)據(jù),和Vue實(shí)例對象上的$emit,$on用法差不多.$bus.$emit("hello",name.value)
}
</script><style scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}
</style>
?另一個(gè)組件:$on接收數(shù)據(jù)
<template><div class="student"><h2>學(xué)生姓名:{{name}}</h2><h2>學(xué)生性別:{{sex}}</h2><button @click="sendStudentName">把學(xué)生名給另一個(gè)組件</button></div>
</template><script setup lang="ts">
import {ref,onMounted) from "vue"
import $bus from "./bus.ts"
let name=ref("張三")
let sex=ref("男")
onMounted(()=>{$bus.$on("hello",(data)=>{name.value=data})})</script><style scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}
</style>