Vue2 的12種組件通訊
下面把每一種組件通信方式的寫(xiě)法一一列出
1. props
父組件向子組件傳送數(shù)據(jù),這應(yīng)該是最常用的方式了
子組件接收到數(shù)據(jù)之后,不能直接修改父組件的數(shù)據(jù)。會(huì)報(bào)錯(cuò),所以當(dāng)父組件重新渲染時(shí),數(shù)據(jù)會(huì)被覆蓋。如果子組件內(nèi)要修改的話推薦使用 computed
// Parent.vue 傳送
<template>
<child :msg="msg"></child>
</template>
// Child.vue 接收
export default {
// 寫(xiě)法一 用數(shù)組接收
props:['msg'],
// 寫(xiě)法二 用對(duì)象接收,可以限定接收的數(shù)據(jù)類型、設(shè)置默認(rèn)值、驗(yàn)證等
props:{
msg:{
type:String,
default:'這是默認(rèn)數(shù)據(jù)'
}
},
mounted(){
console.log(this.msg)
},
}
2. .sync
可以幫我們實(shí)現(xiàn)父組件向子組件傳遞的數(shù)據(jù) 的雙向綁定,所以子組件接收到數(shù)據(jù)后可以直接修改,并且會(huì)同時(shí)修改父組件的數(shù)據(jù)
// Parent.vue
<template>
<child :page.sync="page"></child>
</template>
<script>
export default {
data(){
return {
page:1
}
}
}
// Child.vue
export default {
props:["page"],
computed(){
// 當(dāng)我們?cè)谧咏M件里修改 currentPage 時(shí),父組件的 page 也會(huì)隨之改變
currentPage {
get(){
return this.page
},
set(newVal){
this.$emit("update:page", newVal)
}
}
}
}
</script>
3. v-model
和 .sync 類似,可以實(shí)現(xiàn)將父組件傳給子組件的數(shù)據(jù)為雙向綁定,子組件通過(guò) $emit 修改父組件的數(shù)據(jù)
// Parent.vue
<template>
<child v-model="value"></child>
</template>
<script>
export default {
data(){
return {
value:1
}
}
}
// Child.vue
<template>
<input :value="value" @input="handlerChange">
</template>
export default {
props:["value"],
// 可以修改事件名,默認(rèn)為 input
model:{
event:"updateValue"
},
methods:{
handlerChange(e){
this.$emit("input", e.target.value)
// 如果有上面的重命名就是這樣
this.$emit("updateValue", e.target.value)
}
}
}
</script>
4. ref
ref 如果在普通的DOM元素上,引用指向的就是該DOM元素;
如果在子組件上,引用的指向就是子組件實(shí)例,然后父組件就可以通過(guò) ref 主動(dòng)獲取子組件的屬性或者調(diào)用子組件的方法
// Child.vue
export default {
data(){
return {
name:"沐華"
}
},
methods:{
someMethod(msg){
console.log(msg)
}
}
}
// Parent.vue
<template>
<child ref="child"></child>
</template>
<script>
export default {
mounted(){
const child = this.$refs.child
console.log(child.name) // 沐華
child.someMethod("調(diào)用了子組件的方法")
}
}
</script>
5. $emit / v-on
子組件通過(guò)派發(fā)事件的方式給父組件數(shù)據(jù),或者觸發(fā)父組件更新等操作
// Child.vue 派發(fā)
export default {
data(){
return { msg: "這是發(fā)給父組件的信息" }
},
methods: {
handleClick(){
this.$emit("sendMsg",this.msg)
}
},
}
// Parent.vue 響應(yīng)
<template>
<child v-on:sendMsg="getChildMsg"></child>
// 或 簡(jiǎn)寫(xiě)
<child @sendMsg="getChildMsg"></child>
</template>
export default {
methods:{
getChildMsg(msg){
console.log(msg) // 這是父組件接收到的消息
}
}
}
6. $attrs / $listeners
多層嵌套組件傳遞數(shù)據(jù)時(shí),如果只是傳遞數(shù)據(jù),而不做中間處理的話就可以用這個(gè),比如父組件向?qū)O子組件傳遞數(shù)據(jù)時(shí)
$attrs:包含父作用域里除 class 和 style 除外的非 props 屬性集合。通過(guò) this.$attrs 獲取父作用域中所有符合條件的屬性集合,然后還要繼續(xù)傳給子組件內(nèi)部的其他組件,就可以通過(guò) v-bind="$attrs"
$listeners:包含父作用域里 .native 除外的監(jiān)聽(tīng)事件集合。如果還要繼續(xù)傳給子組件內(nèi)部的其他組件,就可以通過(guò) v-on="$linteners"
使用方式是相同的
// Parent.vue
<template>
<child :name="name" title="1111" ></child>
</template
export default{
data(){
return {
name:"沐華"
}
}
}
// Child.vue
<template>
// 繼續(xù)傳給孫子組件
<sun-child v-bind="$attrs"></sun-child>
</template>
export default{
props:["name"], // 這里可以接收,也可以不接收
mounted(){
// 如果props接收了name 就是 { title:1111 },否則就是{ name:"沐華", title:1111 }
console.log(this.$attrs)
}
}
7. $children / $parent
$children:獲取到一個(gè)包含所有子組件(不包含孫子組件)的 VueComponent 對(duì)象數(shù)組,可以直接拿到子組件中所有數(shù)據(jù)和方法等
$parent:獲取到一個(gè)父節(jié)點(diǎn)的 VueComponent 對(duì)象,同樣包含父節(jié)點(diǎn)中所有數(shù)據(jù)和方法等
// Parent.vue
export default{
mounted(){
this.$children[0].someMethod() // 調(diào)用第一個(gè)子組件的方法
this.$children[0].name // 獲取第一個(gè)子組件中的屬性
}
}
// Child.vue
export default{
mounted(){
this.$parent.someMethod() // 調(diào)用父組件的方法
this.$parent.name // 獲取父組件中的屬性
}
}
8. provide / inject
provide / inject 為依賴注入,說(shuō)是不推薦直接用于應(yīng)用程序代碼中,但是在一些插件或組件庫(kù)里卻是被常用,所以我覺(jué)得用也沒(méi)啥,還挺好用的
provide:可以讓我們指定想要提供給后代組件的數(shù)據(jù)或方法
inject:在任何后代組件中接收想要添加在這個(gè)組件上的數(shù)據(jù)或方法,不管組件嵌套多深都可以直接拿來(lái)用
要注意的是 provide 和 inject 傳遞的數(shù)據(jù)不是響應(yīng)式的,也就是說(shuō)用 inject 接收來(lái)數(shù)據(jù)后,provide 里的數(shù)據(jù)改變了,后代組件中的數(shù)據(jù)不會(huì)改變,除非傳入的就是一個(gè)可監(jiān)聽(tīng)的對(duì)象
所以建議還是傳遞一些常量或者方法
// 父組件
export default{
// 方法一 不能獲取 methods 中的方法
provide:{
name:"沐華",
age: this.data中的屬性
},
// 方法二 不能獲取 data 中的屬性
provide(){
return {
name:"沐華",
someMethod:this.someMethod // methods 中的方法
}
},
methods:{
someMethod(){
console.log("這是注入的方法")
}
}
}
// 后代組件
export default{
inject:["name","someMethod"],
mounted(){
console.log(this.name)
this.someMethod()
}
}
9. EventBus
EventBus 是中央事件總線,不管是父子組件,兄弟組件,跨層級(jí)組件等都可以使用它完成通信操作
定義方式有三種
/方法一:
// 抽離成一個(gè)單獨(dú)的 js 文件 Bus.js ,然后在需要的地方引入 // Bus.js import Vue from "vue" export default new Vue()
方法二 :直接掛載到全局
// main.js import Vue from "vue" Vue.prototype.$bus = new Vue()
方法三 :注入到 Vue 根對(duì)象上
// main.js
import Vue from "vue"
new Vue({
el:"#app",
data:{
Bus: new Vue()
}
})
使用如下,以方法一按需引入為例
// 在需要向外部發(fā)送自定義事件的組件內(nèi)
<template>
<button @click="handlerClick">按鈕</button>
</template>
import Bus from "./Bus.js"
export default{
methods:{
handlerClick(){
// 自定義事件名 sendMsg
Bus.$emit("sendMsg", "這是要向外部發(fā)送的數(shù)據(jù)")
}
}
}
// 在需要接收外部事件的組件內(nèi)
import Bus from "./Bus.js"
export default{
mounted(){
// 監(jiān)聽(tīng)事件的觸發(fā)
Bus.$on("sendMsg", data => {
console.log("這是接收到的數(shù)據(jù):", data)
})
},
beforeDestroy(){
// 取消監(jiān)聽(tīng)
Bus.$off("sendMsg")
}
}
10. Vuex
Vuex 是狀態(tài)管理器,集中式存儲(chǔ)管理所有組件的狀態(tài)。這一塊內(nèi)容過(guò)長(zhǎng),如果基礎(chǔ)不熟的話可以看這個(gè)Vuex,然后大致用法如下
比如創(chuàng)建這樣的文件結(jié)構(gòu)

index.js 里內(nèi)容如下:
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
import state from './state'
import user from './modules/user'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user
},
getters,
actions,
mutations,
state
})
export default store
然后在 main.js 引入:
import Vue from "vue"
import store from "./store"
new Vue({
el:"#app",
store,
render: h => h(App)
})
然后在需要的使用組件里:
import { mapGetters, mapMutations } from "vuex"
export default{
computed:{
// 方式一 然后通過(guò) this.屬性名就可以用了
...mapGetters(["引入getters.js里屬性1","屬性2"])
// 方式二
...mapGetters("user", ["user模塊里的屬性1","屬性2"])
},
methods:{
// 方式一 然后通過(guò) this.屬性名就可以用了
...mapMutations(["引入mutations.js里的方法1","方法2"])
// 方式二
...mapMutations("user",["引入user模塊里的方法1","方法2"])
}
}
// 或者也可以這樣獲取
this.$store.state.xxx
this.$store.state.user.xxx
11. $root
$root 可以拿到 App.vue 里的數(shù)據(jù)和方法
12. slot
就是把子組件的數(shù)據(jù)通過(guò)插槽的方式傳給父組件使用,然后再插回來(lái)
// Child.vue
<template>
<div>
<slot :user="user"></slot>
</div>
</template>
export default{
data(){
return {
user:{ name:"沐華" }
}
}
}
// Parent.vue
<template>
<div>
<child v-slot="slotProps">
{{ slotProps.user.name }}
</child>
</div>
</template>
到此這篇關(guān)于Vue2.x 的12種組件通信的文章就介紹到這了,更多相關(guān)Vue2.x 組件通信內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue長(zhǎng)列表優(yōu)化之虛擬列表實(shí)現(xiàn)過(guò)程詳解
前端的業(yè)務(wù)開(kāi)發(fā)中會(huì)遇到不使用分頁(yè)方式來(lái)加載長(zhǎng)列表的需求,下面這篇文章主要給大家介紹了關(guān)于vue長(zhǎng)列表優(yōu)化之虛擬列表實(shí)現(xiàn)的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
Vue實(shí)現(xiàn)網(wǎng)頁(yè)首屏加載動(dòng)畫(huà)及頁(yè)面內(nèi)請(qǐng)求數(shù)據(jù)加載loading效果
Loading加載動(dòng)畫(huà)組件看起來(lái)很簡(jiǎn)單不重要,實(shí)際上它是保證用戶留存的關(guān)鍵一環(huán),下面這篇文章主要給大家介紹了關(guān)于Vue實(shí)現(xiàn)網(wǎng)頁(yè)首屏加載動(dòng)畫(huà)及頁(yè)面內(nèi)請(qǐng)求數(shù)據(jù)加載loading效果的相關(guān)資料,需要的朋友可以參考下2023-02-02
Vue結(jié)合Element-Plus封裝遞歸組件實(shí)現(xiàn)目錄示例
本文主要介紹了Vue結(jié)合Element-Plus封裝遞歸組件實(shí)現(xiàn)目錄示例,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
Vue3哈希模式實(shí)現(xiàn)錨點(diǎn)導(dǎo)航方式
這篇文章主要介紹了Vue3哈希模式實(shí)現(xiàn)錨點(diǎn)導(dǎo)航方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
vue實(shí)現(xiàn)頁(yè)面div盒子拖拽排序功能
本文主要介紹了vue實(shí)現(xiàn)頁(yè)面div盒子拖拽排序功能,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10

