vue3組件通信方式有以下幾種:porps,$emit, bus,v-model,useAttrs,$ref/$parent,provide/inject,pinia,slot。下面將逐一講解。
??
目錄
1.porps:實現(xiàn)父子組件通信,子組件接收的數(shù)據(jù)還是只讀?
2.$emit
3.全局事件總線 $bus,使用mitt
4.v-model傳值
5. $attrs/useAttrs:獲取組件標簽身上屬性與事件
6.$ref/$parent
7.provide/inject
8.pinia :vuex:集中管理狀態(tài)容器,可以實現(xiàn)任意組件之間的通信
9.slot?插槽分為默認插槽、具名插槽、作用域插槽(可以傳遞數(shù)據(jù)的插槽,子組件可以將數(shù)據(jù)回傳給父組件的插槽)
?
1.porps:實現(xiàn)父子組件通信,子組件接收的數(shù)據(jù)還是只讀
父組件中,引入子組件并給子組件綁定一個money參數(shù)
<template>
<div id="app">
<h1>父組件</h1>
<h3>富一代資產(chǎn){{ money }}元</h3>
<index1 :money="money"></index1>
</div>
</template>
<script lang="ts" setup>
import index1 from './view/index.vue'
import { ref } from 'vue'
let money = ref(1000000000000)
</script>
<style scoped>
#app {
width: 100vw;
height: 100vh;
color: #000;
padding: 50px;
box-sizing: border-box;
}
</style>
子組件中,使用defineProps接收,在template中,可以直接使用money,
<template>
<div class="index1">
<h1>子組件1</h1>
<h3>兒子不知道父親有{{ porps.money }}元</h3>
<h3>
兒子知道了會爭這{{ money }}元(template中可以直接省略porps---script中無法省略?。? </h3>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
// porps:實現(xiàn)父子組件通信,props數(shù)據(jù)還是只讀
// 組合式api 使用 defineProps 接收父子組件傳遞過來的數(shù)據(jù),可以是數(shù)組也可以是對象,
//不需要引入 template中可直接使用
const porps = defineProps(['money'])
console.log(porps)
</script>
<style lang="scss" scoped>
.index1 {
background-color: azure;
padding: 12px;
}
</style>
示例
2.$emit
說到$emit就要說一下自定義事件,在vue框架中事件分為兩種:一種是原生的DOM事件,另外一種自定義事件。原生DOM事件可以讓用戶與網(wǎng)頁進行交互,比如click、dbdlick、change、mouseenter、mouseleave...自定義事件可以實現(xiàn)子組件給父組件傳遞數(shù)據(jù)。vue2中的@click綁定的是自定義事件 ,可以通過.native修飾符變?yōu)樵鶧OM事件?。vue3中綁定的是原生事件,利用defineEmits方法返回函數(shù)觸發(fā)自定義事件,不需要引入,直接使用。
父組件
<template>
<div id="app">
<h1>父組件</h1>
<h3>富一代資產(chǎn){{ money }}元</h3>
<index1 :money="money" @xxx="handlerXXX"></index1>
<h3>{{ son }}</h3>
</div>
</template>
<script lang="ts" setup>
import index1 from './view/index.vue'
import { ref } from 'vue'
let money = ref(1000000000000)
let son = ref('')
const handlerXXX = (value: string) => {
son.value = value
}
</script>
<style scoped>
#app {
width: 100vw;
height: 100vh;
color: #000;
padding: 50px;
box-sizing: border-box;
}
</style>
子組件
<template>
<div class="index1">
<h1>子組件1</h1>
<h3>兒子不知道父親有{{ porps.money }}元</h3>
<h3>
兒子知道了會爭這{{ money }}元(template中可以直接省略porps---script中無法省略?。? </h3>
<p>
vue2中 @click是自定義事件,可以通過.native修飾符變?yōu)樵鶧OM事件。
在vue3中@click是原生DOM事件
</p>
<el-button @click="handlerClick">自定義事件</el-button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
//------porps-------
// porps:實現(xiàn)父子組件通信,props數(shù)據(jù)還是只讀
// 組合式api 使用 defineProps 接收父子組件傳遞過來的數(shù)據(jù),可以是數(shù)組也可以是對象,
//不需要引入 template中可直接使用
const porps = defineProps(['money'])
console.log(porps)
//------$emit-------
//defineEmits方法返回函數(shù)出發(fā)自定義事件,不需要引入 直接使用
const $emit = defineEmits(['xxx'])
const handlerClick = () => {
console.log('觸發(fā)自定義事件')
$emit('xxx', '富二代上交9999元給富一代')
}
</script>
<style lang="scss" scoped>
.index1 {
background-color: azure;
padding: 12px;
}
</style>
?示例:
3.全局事件總線 $bus,使用mitt
Mitt
是一個小巧的JavaScript發(fā)布-訂閱庫,用于在應(yīng)用程序中實現(xiàn)事件監(jiān)聽和觸發(fā)。
安裝:npm install mitt -S
在src目錄下新建bus文件夾,bus文件夾下新建index.ts
// 引入mitt插件 index.ts
import mitt from "mitt"
const $bus = mitt();
export default $bus
?接收組件:引入上面新建的bus,$bus.on? 接收將來兄弟組件傳遞的數(shù)據(jù)
<template>
<div class="index1">
<h1>子組件1</h1>
<p>收到{{ car }}</p>
</div>
</template>
<script setup lang="ts">
import { ref ,onMounted} from 'vue'
// 事件總線 引入$bus
import $bus from '@/bus'
let car = ref('')
// 組件掛載完畢后,當前組件綁定一個事件,接收將來兄弟組件傳遞的數(shù)據(jù)
onMounted(() => {
$bus.on('car', (value: string) => {
car.value = value
})
})
</script>
<style lang="scss" scoped>
.index1 {
background-color: azure;
padding: 12px;
}
</style>
發(fā)送組件:$bus.emit 使用發(fā)送??
<template>
<div class="index2">
<h1>子組件2</h1>
<h3>富二代的親弟錢包有999999元</h3>
<el-button @click="handler">點擊送富二代哥哥法拉利跑車一臺</el-button>
</div>
</template>
<script setup lang="ts">
import $bus from '@/bus'
const handler = () => {
$bus.emit('car', '弟弟送哥哥的法拉利跑車一臺')
}
</script>
<style lang="scss" scoped>
.index2 {
background-color: antiquewhite;
padding: 12px;
margin: 12px 0;
}
</style>
示例:
4.v-model傳值
在vue2中v-model綁定了一個value值,和input事件,并且只能綁定一個v-model。
而在vue3中給子組件傳遞一個porps,并且綁定了一個自定義事件。
此處有兩種用法,方法一?
?porps + @update:money 代表自定義事件。代碼如下:
?父組件代碼:
<template>
<div id="app">
<h1>父組件</h1>
<!-- porps @update:money代表自定義事件,也可以換成其他名字 -->
<!-- v-model
1.相當于子子組件傳遞props[modelValue]
2.相當于給子組件綁定了自定義事件update:modelValue
-->
<index3 :modelValue="money" @update:modelValue="handleMoney"></index3>
<h3>父親60大壽三妹送出價值{{ money3 }}元禮品</h3>
</div>
</template>
<script lang="ts" setup>
import index3 from './view/index3.vue'
import { ref } from 'vue'
// 接收子組件傳遞的數(shù)據(jù)
let money3 = ref(666666)
const handleMoney = (value: number) => {
console.log('接收改變的值:' + value)
money3.value = value
}
</script>
<style scoped>
#app {
width: 100vw;
height: 100vh;
color: #000;
padding: 50px;
box-sizing: border-box;
}
</style>
子組件
<template>
<div class="index3">
<h1>子組件3</h1>
<h3>父親送給三妹 {{ modelValue }}元</h3>
<el-button @click="send">點擊送出</el-button>
</div>
</template>
<script setup lang="ts">
// v-module :收集表單數(shù)據(jù),數(shù)據(jù)雙向綁定,組件之間的通信去實現(xiàn)父子數(shù)據(jù)同步業(yè)務(wù)
defineProps(['modelValue'])
let $emit = defineEmits(['update:modelValue'])
const send = () => {
$emit('update:modelValue', 9999)
}
</script>
<style lang="scss" scoped>
.index3 {
background-color: beige;
padding: 12px;
}
</style>
?方法二
1.相當于給子組件傳遞一個porps[modelValue]=666666 (一定叫modelValue)
2.相當于給子組件綁定了一個自定義事件,事件名一定是 update:modelValue,父組件不用自己寫自定義事件
父組件代碼
<template>
<div id="app">
<h1>父組件</h1>
<!-- v-model使用情況:1.相當于給子組件傳遞一個porps[modelValue]=100000 (一定叫modelValue)
2.相當于給子組件綁定了一個自定義事件,事件名一定是 update:modelValue
與vue2的v-model的區(qū)別在于,vue2的v-model綁定了一個value值,和input事件,?? vue2中只能綁定一個v-model,而vue3 可以綁定多個v-model
-->
<index3 v-model="money3" v-model:name="name" v-model:age="age"></index3>
<h3>父親60大壽三妹送出價值{{ money3 }}元禮品</h3>
</div>
</template>
<script lang="ts" setup>
import index3 from './view/index3.vue'
import { ref } from 'vue'
let money3 = ref(666666)
let name = ref('嘉達')
let age = ref(20)
</script>
<style scoped>
#app {
width: 100vw;
height: 100vh;
color: #000;
padding: 50px;
box-sizing: border-box;
}
</style>
子組件:
注意:以v-model="money3"的形式傳遞時,使用defineProps 接收名字只能叫modelValue,默認寫法。
傳多個值時,父組件?以v-model:參數(shù)名="參數(shù)名" 形式傳遞,defineProps 接收名字就是參數(shù)名。
更改數(shù)據(jù)使用defineEmits,默認方式更改值 事件名字只能叫 “update:modelValue”,
更改指定名字的值時 事件名字 是 “update:參數(shù)名”
<template>
<div class="index3">
<h1>子組件3</h1>
<h3>父親送給三妹 {{ modelValue }}元</h3>
<h3>名字:{{ name }}</h3>
<h3>年齡:{{ age }}</h3>
<el-button @click="send">點擊送出</el-button>
<el-button @click="changeName">點擊更改名字和年齡</el-button>
</div>
</template>
<script setup lang="ts">
// v-module :收集表單數(shù)據(jù),數(shù)據(jù)雙向綁定,組件之間的通信去實現(xiàn)父子數(shù)據(jù)同步業(yè)務(wù)
defineProps(['modelValue', 'name', 'age'])
let $emit = defineEmits(['update:modelValue', 'update:name', 'update:age'])
const send = () => {
$emit('update:modelValue', 9999)
}
const changeName = () => {
$emit('update:name', '翠花')
$emit('update:age', 18)
}
</script>
<style lang="scss" scoped>
.index3 {
background-color: beige;
padding: 12px;
}
</style>
?
5. $attrs/useAttrs:獲取組件標簽身上屬性與事件
父組件
<template>
<div id="app">
<h1>父組件</h1>
<index4 type="primary" size="large" @click="handlerIndex4"></index4>
</div>
</template>
<script lang="ts" setup>
import index4 from './view/index4.vue'
import { ref } from 'vue'
// useAttrs
let handlerIndex4Value = ref('')
const handlerIndex4 = (value: string) => {
handlerIndex4Value.value = value
}
</script>
<style scoped>
#app {
width: 100vw;
height: 100vh;
color: #000;
padding: 50px;
box-sizing: border-box;
}
</style>
子組件:?
在?<script setup>
?使用??attrs
?的情況應(yīng)該是相對來說較為罕見的,因為可以在模板中直接通過?$attrs
?來訪問。在你的確需要使用它們的罕見場景中,可以?useAttrs
? 輔助函數(shù)。
?porps和useAttrs都可以接收來自父組件傳遞過來的屬性與屬性值, 如果同時用porps接收值 ,那么useAttrs方法就無法再次獲取,porps優(yōu)先級高與useAttrs。? useAttr同時可以接收事件。
<template>
<div class="index4">
<h1>子組件4</h1>
<el-button type="primary" :="$attrs">
useAttrs通信 :="$attrs"等價于 v-bind:{type:'primary' , size:'large' }
</el-button>
</div>
</template>
<script setup lang="ts">
// 引入useAttrs方法:獲取組件標簽身上屬性與事件
import { useAttrs } from 'vue'
// 此方法會返回一個對象
let $attrs:any = useAttrs()
// console.log($attrs)
// 獲取身上的事件
$attrs.onClick('接收事件回調(diào)參數(shù)')
</script>
<style lang="scss" scoped>
.index4 {
background-color: rgb(240, 177, 246);
padding: 12px;
margin: 12px 0;
}
</style>
示例?
6.$ref/$parent
ref:可以獲取真實的DOM節(jié)點,可以獲取子組件實例的VC
$parent:可以在子組件內(nèi)部獲取到父組件的實例
組件內(nèi)部的數(shù)據(jù)對外是關(guān)閉的,不能直接訪問。需要使用defineExpose對外暴露
<template>
<div id="app">
<h1>父組件</h1>
<el-button @click="borrow" style="margin: 12px 0">
父親找5兒子借1元
</el-button>
<h3>父親資產(chǎn){{ money }}元</h3>
<index5 ref="son5"></index5>
</div>
</template>
<script lang="ts" setup>
import index5 from './view/index5.vue'
import { ref } from 'vue'
let money = ref(1000000000000)
// $ref
let son5 = ref() //此處必須與組件綁定的ref名字相同
// 借錢方法=> 父親找兒子借錢,兒子的錢變少,父親的錢變多 使用$ref 獲取子組件數(shù)據(jù)
const borrow = () => {
money.value++
// 獲取數(shù)據(jù)
son5.value.money--
// 隨后5兒子買包送人 --調(diào)用方法
son5.value.buy()
}
defineExpose({ money })
</script>
<style scoped>
#app {
width: 100vw;
height: 100vh;
color: #000;
padding: 50px;
box-sizing: border-box;
}
</style>
子組件
<template>
<div class="index5">
<h1>子組件5</h1>
<h3>ref:可以獲取真實的DOM節(jié)點,可以獲取子組件實例的VC</h3>
<h3>$parent:可以在子組件內(nèi)部獲取到父組件的實例</h3>
<h3>兒子剩余{{ money }}元</h3>
<el-button @click="borrowMoney($parent)">
投資買樓資金不足,找爸爸要90000000(點擊按鈕注入$parent)
</el-button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
let money = ref(88888888)
// 買包
const buy = () => {
money.value = money.value - 15862
}
// 找老爸要錢
const borrowMoney = ($parent: any) => {
console.log($parent)
// 獲取父組件數(shù)據(jù)
$parent.money = $parent.money - 90000000
money.value = money.value + 90000000
}
// 組件內(nèi)部的數(shù)據(jù)對外是關(guān)閉的,不能直接訪問。需要使用defineExpose對外暴露
defineExpose({ money, buy })
</script>
<style lang="scss" scoped>
.index5 {
background-color: rgb(226, 226, 226);
padding: 12px;
}
</style>
示例
7.provide/inject
? 1. vue3提供 provide (提供)與 inject (注入),事件隔輩組件數(shù)據(jù)傳遞。
? 2. 父組件提供數(shù)據(jù)(provide)需要兩個參數(shù):
? ? 第一個參數(shù)就是提供數(shù)據(jù)的key
? ? 第二個參數(shù)是提供的數(shù)據(jù)
? 3. 注入祖先組件提供的數(shù)據(jù):提供的key
? 4. inject獲取的數(shù)據(jù)是指向同一個對象,可以進行修改
<template>
<div id="app">
<h1>父組件</h1>
<index6></index6>
</div>
</template>
<script lang="ts" setup>
import index6 from './view/index6.vue'
import { provide } from 'vue'
// provide與inject
provide('gold', 5678)
</script>
<style scoped>
#app {
width: 100vw;
height: 100vh;
color: #000;
padding: 50px;
box-sizing: border-box;
}
</style>
子組件
<template>
<div class="index6">
<h1>子組件6</h1>
<index6_1></index6_1>
</div>
</template>
<script setup lang="ts">
import index6_1 from './index6_1.vue'
</script>
<style lang="scss" scoped>
.index6 {
background-color: rgb(234, 139, 255);
padding: 12px;
margin: 12px 0;
}
</style>
孫子組件
<template>
<div class="index6_1">
<h2>孫子組件</h2>
<h3>收到爺爺送的黃金{{ gold }}g</h3>
</div>
</template>
<script setup lang="ts">
import { inject } from 'vue'
let gold = inject('gold')
console.log(gold)
</script>
<style lang="scss" scoped>
.index6_1 {
background-color: rgb(233, 229, 114);
padding: 12px;
}
</style>
示例?
8.pinia :vuex:集中管理狀態(tài)容器,可以實現(xiàn)任意組件之間的通信
? ?Pinia | Pinia官網(wǎng)
?核心概念 state mutations actions getters modules
?pinia 核心概念 state actions getters
?pinia分為兩種寫法,選擇式api 寫法=>類似與vuex 和組合式api寫法
8.1.安裝
yarn add pinia
# 或者使用 npm
npm install pinia
8.2.新建store文件夾,如下,分為兩個模塊講解 選擇式api寫法 與 組合式api寫法
8.3.index.ts?
// 創(chuàng)建大倉庫 index.ts
import { createPinia } from 'pinia'
// createPinia
let store =createPinia();
// 對外暴露
export default store
8.4.main.js? : 引入?"./store"
import { createApp } from 'vue'
import App from "@/App.vue"
import "@/assets/style/common.scss"
import store from "./store"
const app = createApp(App)
app.use(store)
app.mount('#app')
8.5.user.ts?選擇式api寫法
// 定義user倉庫 選擇式api寫法 user.ts
import { defineStore } from "pinia";
// defineStore傳入兩個參數(shù) 第一個是小倉庫的名字,第二個是小倉庫配置對象。
// defineStore方法執(zhí)行會返回一個函數(shù),函數(shù)作用就是讓組件可以獲取到倉庫的數(shù)據(jù)
let userStore = defineStore("user", {
// 存儲數(shù)據(jù):state
state: () => {
return {
name: "梅賽德斯",
arr: [12, 234, 23434, 34534]
}
},
actions: {
// 注意函數(shù)沒有context上下文對象,沒有commit 沒有mutation去修改數(shù)據(jù)
// 此處使用this就是小倉庫對象--- 此處不能使用箭頭函數(shù)
updateName(value: string) {
this.name = value
}
},
getters: {
totalMoney() {
let M: any = this.arr.reduce((prev: number, next: number) => {
return prev + next
}, 0)
return M
}
}
})
export default userStore
?8.6.info.ts?組合式api寫法
// 定義info倉庫 組合式api寫法 info.ts
import { defineStore } from "pinia";
import { ref, computed } from "vue"
let infoStore = defineStore("info", () => {
// 此處的箭頭函數(shù)務(wù)必返回一個對象,屬性與方法提供給組件使用
// 主要用到了vue3中的組合式API函數(shù)
let num = ref(34233)
const updateNum = (value: number) => {
num.value = value
}
// 使用計算屬性
const newNum = computed(() => {
return num.value * 1000
})
return {
num,
newNum,
updateNum
}
})
export default infoStore
使用:
<template>
<div class="index7">
<h1>子組件7</h1>
<h3>名字:{{ userInfo.name }}</h3>
<h3>{{ userInfo.totalMoney }}</h3>
<h4>組合式api:{{ info.num }}</h4>
<h4>組合式api使用計算屬性:{{ info.newNum }}</h4>
<el-button @click="changeName">點擊改名字</el-button>
<el-button @click="changeInfo">點擊改num</el-button>
</div>
</template>
<script setup lang="ts">
import userStore from '@/store/modules/user'
import infoStore from '@/store/modules/info'
// vuex:集中管理狀態(tài)容器,可以實現(xiàn)任意組件之間的通信
// 核心概念 state mutations actions getters modules
// pinia 核心概念 state actions getters
// pinia分為兩種寫法,選擇式api 寫法=>類似與vuex 和組合式api寫法
let userInfo = userStore()
const changeName = () => {
userInfo.updateName('庫里南')
}
// 獲取
let info = infoStore()
console.log(info)
const changeInfo = () => {
info.updateNum(77777)
}
</script>
<style lang="scss" scoped>
.index7 {
background-color: rgb(115, 244, 175);
padding: 12px;
margin: 12px 0;
}
</style>
示例
9.slot?插槽分為默認插槽、具名插槽、作用域插槽(可以傳遞數(shù)據(jù)的插槽,子組件可以將數(shù)據(jù)回傳給父組件的插槽)
9.1 默認插槽 -父組件
<template>
<div id="app">
<h1>父組件</h1>
<index8 >
<div>1.我是默認插槽</div>
</index8>
</div>
</template>
<script lang="ts" setup>
import index8 from './view/index8.vue'
</script>
子組件
<template>
<div class="index8">
<h1>子組件8</h1>
<!-- 默認插槽 -->
<slot></slot>
</div>
</template>
<script setup lang="ts">
</script>
</style>
?9.2 具名插槽 -父組件
<template>
<div id="app">
<h1>父組件</h1>
<index8 >
<template v-slot:lora>
<div> 我是具名插槽數(shù)據(jù)lora</div>
</template>
<!-- 具名插槽可簡化為# -->
<template #Marry>
<div> 我是具名插槽數(shù)據(jù)Marry</div>
</template>
</index8>
</div>
</template>
<script lang="ts" setup>
import index8 from './view/index8.vue'
</script>
子組件
<template>
<div class="index8">
<h1>子組件8</h1>
<!-- 默認插槽 -->
<slot name="lora"></slot>
<p>-------</p>
<slot name="Marry"></slot>
<p>-------</p>
</div>
</template>
<script setup lang="ts">
</script>
</style>
??9.3 作用域插槽 -父組件
<template>
<div id="app">
<h1>父組件</h1>
<index8 :slotList="slotList">
<template v-slot="{ $row, $index }">
<span>
{{ $row.type === 1 ? $row.name : $row.lable }}
index:{{ $index }}
</span>
</template>
</index8>
</div>
</template>
<script lang="ts" setup>
import index8 from './view/index8.vue'
let slotList = [
{
id: 1,
lable: '歐坤',
name: '歐坤name',
type: 1,
},
{
id: 2,
lable: '歐坤東方',
type: 0,
},
{
id: 4,
lable: '歐坤西南',
type: 0,
},
]
</script>
子組件
<template>
<div class="index8">
<h1>子組件8</h1>
<div>
<div v-for="(item, index) in slotList" :key="item.id">
<slot :$row="item" :$index="index"></slot>
</div>
</div>
</div>
</template>
<script setup lang="ts">
defineProps(['slotList'])
</script>
</style>
示例?
文章來源:http://www.zghlxwxcb.cn/news/detail-470086.html
以上是總結(jié)的所有通信方式?文章來源地址http://www.zghlxwxcb.cn/news/detail-470086.html
到了這里,關(guān)于vue3組件通信詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!