Vue2和Vue3的10種組件通信方式梳理
Vue中組件通信方式有很多,其中Vue2和Vue3實(shí)現(xiàn)起來(lái)也會(huì)有很多差異;本文將通過(guò)選項(xiàng)式API 組合式API以及setup三種不同實(shí)現(xiàn)方式全面介紹Vue2和Vue3的組件通信方式。
其中將要實(shí)現(xiàn)的通信方式如下表所示:
| 方式 | Vue2 | Vue3 |
|---|---|---|
| 父?jìng)髯?/td> | props | props |
| 子傳父 | $emit | emits |
| 父?jìng)髯?/td> | $attrs | attrs |
| 子傳父 | $listeners | 無(wú)(合并到 attrs方式) |
| 父?jìng)髯?/td> | provide/inject | provide/inject |
| 子組件訪問(wèn)父組件 | $parent | 無(wú) |
| 父組件訪問(wèn)子組件 | $children | 無(wú) |
| 父組件訪問(wèn)子組件 | $ref | expose&ref |
| 兄弟傳值 | EventBus | mitt |
props
props是組件通信中最常用的通信方式之一。父組件通過(guò)v-bind傳入,子組件通過(guò)props接收,下面是它的三種實(shí)現(xiàn)方式
選項(xiàng)式API:
//父組件
<template>
<div>
<Child :msg="parentMsg" />
</div>
</template>
<script>
import Child from './Child'
export default {
components:{
Child
},
data() {
return {
parentMsg: '父組件信息'
}
}
}
</script>
//子組件
<template>
<div>
{{msg}}
</div>
</template>
<script>
export default {
props:['msg']
}
</script>組合式Api:
//父組件
<template>
<div>
<Child :msg="parentMsg" />
</div>
</template>
<script>
import { ref,defineComponent } from 'vue'
import Child from './Child.vue'
export default defineComponent({
components:{
Child
},
setup() {
const parentMsg = ref('父組件信息')
return {
parentMsg
};
},
});
</script>
//子組件
<template>
<div>
{{ parentMsg }}
</div>
</template>
<script>
import { defineComponent,toRef } from "vue";
export default defineComponent({
props: ["msg"],// 如果這行不寫(xiě),下面就接收不到
setup(props) {
console.log(props.msg) //父組件信息
let parentMsg = toRef(props, 'msg')
return {
parentMsg
};
},
});
</script>setup語(yǔ)法糖:
//父組件
<template>
<div>
<Child :msg="parentMsg" />
</div>
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const parentMsg = ref('父組件信息')
</script>
//子組件
<template>
<div>
{{ parentMsg }}
</div>
</template>
<script setup>
import { toRef, defineProps } from "vue";
const props = defineProps(["msg"]);
console.log(props.msg) //父組件信息
let parentMsg = toRef(props, 'msg')
</script>注意:props中數(shù)據(jù)流是單項(xiàng)的,即子組件不可改變父組件傳來(lái)的值
在組合式API中,如果想在子組件中用其它變量接收props的值時(shí)需要使用toRef將props中的屬性轉(zhuǎn)為響應(yīng)式。
emit
子組件可以通過(guò)emit發(fā)布一個(gè)事件并傳遞一些參數(shù),父組件通過(guò)v-on進(jìn)行這個(gè)事件的監(jiān)聽(tīng)
選項(xiàng)式API:
//父組件
<template>
<div>
<Child @sendMsg="getFromChild" />
</div>
</template>
<script>
import Child from './Child'
export default {
components:{
Child
},
methods: {
getFromChild(val) {
console.log(val) //我是子組件數(shù)據(jù)
}
}
}
</script>
// 子組件
<template>
<div>
<button @click="sendFun">send</button>
</div>
</template>
<script>
export default {
methods:{
sendFun(){
this.$emit('sendMsg','我是子組件數(shù)據(jù)')
}
}
}
</script>組合式Api:
//父組件
<template>
<div>
<Child @sendMsg="getFromChild" />
</div>
</template>
<script>
import Child from './Child'
import { defineComponent } from "vue";
export default defineComponent({
components: {
Child
},
setup() {
const getFromChild = (val) => {
console.log(val) //我是子組件數(shù)據(jù)
}
return {
getFromChild
};
},
});
</script>
//子組件
<template>
<div>
<button @click="sendFun">send</button>
</div>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
emits: ['sendMsg'],
setup(props, ctx) {
const sendFun = () => {
ctx.emit('sendMsg', '我是子組件數(shù)據(jù)')
}
return {
sendFun
};
},
});
</script>setup語(yǔ)法糖:
//父組件
<template>
<div>
<Child @sendMsg="getFromChild" />
</div>
</template>
<script setup>
import Child from './Child'
const getFromChild = (val) => {
console.log(val) //我是子組件數(shù)據(jù)
}
</script>
//子組件
<template>
<div>
<button @click="sendFun">send</button>
</div>
</template>
<script setup>
import { defineEmits } from "vue";
const emits = defineEmits(['sendMsg'])
const sendFun = () => {
emits('sendMsg', '我是子組件數(shù)據(jù)')
}
</script>attrs和listeners
子組件使用$attrs可以獲得父組件除了props傳遞的屬性和特性綁定屬性 (class和 style)之外的所有屬性。
子組件使用$listeners可以獲得父組件(不含.native修飾器的)所有v-on事件監(jiān)聽(tīng)器,在Vue3中已經(jīng)不再使用;但是Vue3中的attrs不僅可以獲得父組件傳來(lái)的屬性也可以獲得父組件v-on事件監(jiān)聽(tīng)器
選項(xiàng)式API:
//父組件
<template>
<div>
<Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" />
</div>
</template>
<script>
import Child from './Child'
export default {
components:{
Child
},
data(){
return {
msg1:'子組件msg1',
msg2:'子組件msg2'
}
},
methods: {
parentFun(val) {
console.log(`父組件方法被調(diào)用,獲得子組件傳值:${val}`)
}
}
}
</script>
//子組件
<template>
<div>
<button @click="getParentFun">調(diào)用父組件方法</button>
</div>
</template>
<script>
export default {
methods:{
getParentFun(){
this.$listeners.parentFun('我是子組件數(shù)據(jù)')
}
},
created(){
//獲取父組件中所有綁定屬性
console.log(this.$attrs) //{"msg1": "子組件msg1","msg2": "子組件msg2"}
//獲取父組件中所有綁定方法
console.log(this.$listeners) //{parentFun:f}
}
}
</script>組合式API:
//父組件
<template>
<div>
<Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" />
</div>
</template>
<script>
import Child from './Child'
import { defineComponent,ref } from "vue";
export default defineComponent({
components: {
Child
},
setup() {
const msg1 = ref('子組件msg1')
const msg2 = ref('子組件msg2')
const parentFun = (val) => {
console.log(`父組件方法被調(diào)用,獲得子組件傳值:${val}`)
}
return {
parentFun,
msg1,
msg2
};
},
});
</script>
//子組件
<template>
<div>
<button @click="getParentFun">調(diào)用父組件方法</button>
</div>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
emits: ['sendMsg'],
setup(props, ctx) {
//獲取父組件方法和事件
console.log(ctx.attrs) //Proxy {"msg1": "子組件msg1","msg2": "子組件msg2"}
const getParentFun = () => {
//調(diào)用父組件方法
ctx.attrs.onParentFun('我是子組件數(shù)據(jù)')
}
return {
getParentFun
};
},
});
</script>setup語(yǔ)法糖:
//父組件
<template>
<div>
<Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" />
</div>
</template>
<script setup>
import Child from './Child'
import { ref } from "vue";
const msg1 = ref('子組件msg1')
const msg2 = ref('子組件msg2')
const parentFun = (val) => {
console.log(`父組件方法被調(diào)用,獲得子組件傳值:${val}`)
}
</script>
//子組件
<template>
<div>
<button @click="getParentFun">調(diào)用父組件方法</button>
</div>
</template>
<script setup>
import { useAttrs } from "vue";
const attrs = useAttrs()
//獲取父組件方法和事件
console.log(attrs) //Proxy {"msg1": "子組件msg1","msg2": "子組件msg2"}
const getParentFun = () => {
//調(diào)用父組件方法
attrs.onParentFun('我是子組件數(shù)據(jù)')
}
</script>注意:Vue3中使用attrs調(diào)用父組件方法時(shí),方法前需要加上on;如parentFun->onParentFun
provide/inject
provide:是一個(gè)對(duì)象,或者是一個(gè)返回對(duì)象的函數(shù)。里面包含要給子孫后代屬性
inject:一個(gè)字符串?dāng)?shù)組,或者是一個(gè)對(duì)象。獲取父組件或更高層次的組件provide的值,既在任何后代組件都可以通過(guò)inject獲得
選項(xiàng)式API:
//父組件
<script>
import Child from './Child'
export default {
components: {
Child
},
data() {
return {
msg1: '子組件msg1',
msg2: '子組件msg2'
}
},
provide() {
return {
msg1: this.msg1,
msg2: this.msg2
}
}
}
</script>
//子組件
<script>
export default {
inject:['msg1','msg2'],
created(){
//獲取高層級(jí)提供的屬性
console.log(this.msg1) //子組件msg1
console.log(this.msg2) //子組件msg2
}
}
</script>組合式API:
//父組件
<script>
import Child from './Child'
import { ref, defineComponent,provide } from "vue";
export default defineComponent({
components:{
Child
},
setup() {
const msg1 = ref('子組件msg1')
const msg2 = ref('子組件msg2')
provide("msg1", msg1)
provide("msg2", msg2)
return {
}
},
});
</script>
//子組件
<template>
<div>
<button @click="getParentFun">調(diào)用父組件方法</button>
</div>
</template>
<script>
import { inject, defineComponent } from "vue";
export default defineComponent({
setup() {
console.log(inject('msg1').value) //子組件msg1
console.log(inject('msg2').value) //子組件msg2
},
});
</script>- setup語(yǔ)法糖
//父組件
<script setup>
import Child from './Child'
import { ref,provide } from "vue";
const msg1 = ref('子組件msg1')
const msg2 = ref('子組件msg2')
provide("msg1",msg1)
provide("msg2",msg2)
</script>
//子組件
<script setup>
import { inject } from "vue";
console.log(inject('msg1').value) //子組件msg1
console.log(inject('msg2').value) //子組件msg2
</script>說(shuō)明;provide/inject一般在深層組件嵌套中使用合適。一般在組件開(kāi)發(fā)中用的居多。
parent/children
$parent: 子組件獲取父組件Vue實(shí)例,可以獲取父組件的屬性方法等
$children: 父組件獲取子組件Vue實(shí)例,是一個(gè)數(shù)組,是直接兒子的集合,但并不保證子組件的順序
Vue2:
import Child from './Child'
export default {
components: {
Child
},
created(){
console.log(this.$children) //[Child實(shí)例]
console.log(this.$parent)//父組件實(shí)例
}
}注意 父組件獲取到的$children并不是響應(yīng)式的
expose&ref
$refs可以直接獲取元素屬性,同時(shí)也可以直接獲取子組件實(shí)例
選項(xiàng)式API:
//父組件
<template>
<div>
<Child ref="child" />
</div>
</template>
<script>
import Child from './Child'
export default {
components: {
Child
},
mounted(){
//獲取子組件屬性
console.log(this.$refs.child.msg) //子組件元素
//調(diào)用子組件方法
this.$refs.child.childFun('父組件信息')
}
}
</script>
//子組件
<template>
<div>
<div></div>
</div>
</template>
<script>
export default {
data(){
return {
msg:'子組件元素'
}
},
methods:{
childFun(val){
console.log(`子組件方法被調(diào)用,值${val}`)
}
}
}
</script>組合式API:
//父組件
<template>
<div>
<Child ref="child" />
</div>
</template>
<script>
import Child from './Child'
import { ref, defineComponent, onMounted } from "vue";
export default defineComponent({
components: {
Child
},
setup() {
const child = ref() //注意命名需要和template中ref對(duì)應(yīng)
onMounted(() => {
//獲取子組件屬性
console.log(child.value.msg) //子組件元素
//調(diào)用子組件方法
child.value.childFun('父組件信息')
})
return {
child //必須return出去 否則獲取不到實(shí)例
}
},
});
</script>
//子組件
<template>
<div>
</div>
</template>
<script>
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
const msg = ref('子組件元素')
const childFun = (val) => {
console.log(`子組件方法被調(diào)用,值${val}`)
}
return {
msg,
childFun
}
},
});
</script>setup語(yǔ)法糖:
//父組件
<template>
<div>
<Child ref="child" />
</div>
</template>
<script setup>
import Child from './Child'
import { ref, onMounted } from "vue";
const child = ref() //注意命名需要和template中ref對(duì)應(yīng)
onMounted(() => {
//獲取子組件屬性
console.log(child.value.msg) //子組件元素
//調(diào)用子組件方法
child.value.childFun('父組件信息')
})
</script>
//子組件
<template>
<div>
</div>
</template>
<script setup>
import { ref,defineExpose } from "vue";
const msg = ref('子組件元素')
const childFun = (val) => {
console.log(`子組件方法被調(diào)用,值${val}`)
}
//必須暴露出去父組件才會(huì)獲取到
defineExpose({
childFun,
msg
})
</script>注意:通過(guò)ref獲取子組件實(shí)例必須在頁(yè)面掛載完成后才能獲取。
在使用setup語(yǔ)法糖時(shí)候,子組件必須元素或方法暴露出去父組件才能獲取到
EventBus/mitt
兄弟組件通信可以通過(guò)一個(gè)事件中心EventBus實(shí)現(xiàn),既新建一個(gè)Vue實(shí)例來(lái)進(jìn)行事件的監(jiān)聽(tīng),觸發(fā)和銷(xiāo)毀。
在Vue3中沒(méi)有了EventBus兄弟組件通信,但是現(xiàn)在有了一個(gè)替代的方案mitt.js,原理還是 EventBus
選項(xiàng)式API:
//組件1
<template>
<div>
<button @click="sendMsg">傳值</button>
</div>
</template>
<script>
import Bus from './bus.js'
export default {
data(){
return {
msg:'子組件元素'
}
},
methods:{
sendMsg(){
Bus.$emit('sendMsg','兄弟的值')
}
}
}
</script>
//組件2
<template>
<div>
組件2
</div>
</template>
<script>
import Bus from './bus.js'
export default {
created(){
Bus.$on('sendMsg',(val)=>{
console.log(val);//兄弟的值
})
}
}
</script>
//bus.js
import Vue from "vue"
export default new Vue()組合式API:
首先安裝mitt
npm i mitt -S
然后像Vue2中bus.js一樣新建mitt.js文件
mitt.js
import mitt from 'mitt' const Mitt = mitt() export default Mitt
//組件1
<template>
<button @click="sendMsg">傳值</button>
</template>
<script>
import { defineComponent } from "vue";
import Mitt from './mitt.js'
export default defineComponent({
setup() {
const sendMsg = () => {
Mitt.emit('sendMsg','兄弟的值')
}
return {
sendMsg
}
},
});
</script>
//組件2
<template>
<div>
組件2
</div>
</template>
<script>
import { defineComponent, onUnmounted } from "vue";
import Mitt from './mitt.js'
export default defineComponent({
setup() {
const getMsg = (val) => {
console.log(val);//兄弟的值
}
Mitt.on('sendMsg', getMsg)
onUnmounted(() => {
//組件銷(xiāo)毀 移除監(jiān)聽(tīng)
Mitt.off('sendMsg', getMsg)
})
},
});
</script>- setup語(yǔ)法糖
//組件1
<template>
<button @click="sendMsg">傳值</button>
</template>
<script setup>
import Mitt from './mitt.js'
const sendMsg = () => {
Mitt.emit('sendMsg', '兄弟的值')
}
</script>
//組件2
<template>
<div>
組件2
</div>
</template>
<script setup>
import { onUnmounted } from "vue";
import Mitt from './mitt.js'
const getMsg = (val) => {
console.log(val);//兄弟的值
}
Mitt.on('sendMsg', getMsg)
onUnmounted(() => {
//組件銷(xiāo)毀 移除監(jiān)聽(tīng)
Mitt.off('sendMsg', getMsg)
})
</script>寫(xiě)在最后
其實(shí)組件還可以借助Vuex或者Pinia狀態(tài)管理工具進(jìn)行通信(但是組件之間的通信一般不建議這樣做,因?yàn)檫@樣就會(huì)出現(xiàn)組件不能復(fù)用的問(wèn)題)。對(duì)于Vuex和Pinia的用法大家可以參考這篇文章文詳解Pinia和Vuex與兩個(gè)Vue狀態(tài)管理模式
到此這篇關(guān)于Vue2和Vue3的10種組件通信方式梳理的文章就介紹到這了,更多相關(guān)Vue組件通信內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
el-tree使用獲取當(dāng)前選中節(jié)點(diǎn)的父節(jié)點(diǎn)數(shù)據(jù)
本文主要介紹了el-tree使用獲取當(dāng)前選中節(jié)點(diǎn)的父節(jié)點(diǎn)數(shù)據(jù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-10-10
vue項(xiàng)目中使用fetch的實(shí)現(xiàn)方法
這篇文章主要介紹了vue項(xiàng)目中使用fetch的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
vue+drf+第三方滑動(dòng)驗(yàn)證碼接入的實(shí)現(xiàn)
這篇文章要給大家介紹的是vue和drf以及第三方滑動(dòng)驗(yàn)證碼接入的實(shí)現(xiàn),下文小編講詳細(xì)講解該內(nèi)容,感興趣的小伙伴可以和小編一起來(lái)學(xué)習(xí)奧2021-10-10
vue在mounted中window.onresize不生效問(wèn)題及解決
這篇文章主要介紹了vue中在mounted中window.onresize不生效問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue項(xiàng)目History模式404問(wèn)題解決方法
本文主要解決Vue項(xiàng)目使用History模式發(fā)布到服務(wù)器Nginx上刷新頁(yè)面404問(wèn)題。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
vue?parseHTML?函數(shù)源碼解析AST基本形成
這篇文章主要為大家介紹了vue?parseHTML?函數(shù)源碼解析AST基本形成,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
vue請(qǐng)求服務(wù)器數(shù)據(jù)后綁定不上的解決方法
今天小編就為大家分享一篇vue請(qǐng)求服務(wù)器數(shù)據(jù)后綁定不上的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-10-10
Vue3之組件狀態(tài)保持KeepAlive的簡(jiǎn)單使用
這篇文章主要介紹了Vue3之組件狀態(tài)保持KeepAlive的簡(jiǎn)單使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
vue2+elementui的el-table固定列會(huì)遮住橫向滾動(dòng)條及錯(cuò)位問(wèn)題解決方案
這篇文章主要介紹了vue2+elementui的el-table固定列會(huì)遮住橫向滾動(dòng)條及錯(cuò)位問(wèn)題解決方案,主要解決固定列錯(cuò)位后, 接下來(lái)就是把固定列往上提滾動(dòng)條的高度就不會(huì)影響了,需要的朋友可以參考下2024-01-01

