vue父子組件相互通信方法示例梳理總結(jié)
一、props(父向子傳值----自定義屬性) / $emit(子向父?jìng)髦?---- 自定義事件)
父組件通過props
的方式向子組件傳遞數(shù)據(jù),而通過$emit
子組件可以向父組件通信。
1. 父組件向子組件傳值(props)
下面通過一個(gè)例子說明父組件如何向子組件傳遞數(shù)據(jù):在子組件article.vue
中如何獲取父組件section.vue
中的數(shù)據(jù)articles:['紅樓夢(mèng)', '西游記','三國(guó)演義']
// section父組件 <template> <div class="section"> <com-article :articles="articleList"></com-article> </div> </template> <script> import comArticle from './test/article.vue' export default { name: 'HelloWorld', components: { comArticle }, data() { return { articleList: ['紅樓夢(mèng)', '西游記', '三國(guó)演義'] } }} </script> // 子組件 article.vue <template> <div> <span v-for="(item, index) in articles" :key="index">{{item}}</span> </div> </template> <script> export default { props: ['articles']} </script>
注意: prop 可以從上一級(jí)組件傳遞到下一級(jí)組件(父子組件),即所謂的單向數(shù)據(jù)流。而且 prop 只讀,不可被修改,強(qiáng)行修改能生效,但是控制臺(tái)會(huì)有錯(cuò)誤信息。
在子組件修改父組件傳入的值的方法:
1 .sync 父組件v-on綁定自定義屬性時(shí)添加修飾符.sync 在子組件中通過調(diào)用emit(′update:自定義屬性′,要修改的新值)==>emit('update:自定義屬性',新值) 固定寫法 此時(shí)子組件中接收的值就更新成了新值(父組件中的原始值會(huì)跟著變化,控制臺(tái)不會(huì)報(bào)錯(cuò))
父組件中: <child :value.sync='xxx'/>
子組件中: this.$emit('update:value',yyy)
2.在子組件data中聲明自己的數(shù)據(jù),讓接收的數(shù)據(jù)作為這個(gè)數(shù)據(jù)的值 ==> 子組件的數(shù)據(jù)=this.value
(這種方法實(shí)際修改的是自己的數(shù)據(jù) 父組件的數(shù)據(jù)沒變)
子組件的data中: 1.接收傳入的數(shù)據(jù): props:['value']
? 2.newValue=this.value
3.父組件傳值時(shí)傳遞一個(gè)引用類型,在子組件中修改引用類型的屬性值并不會(huì)改變?cè)撘妙愋驮诙阎械牡刂?/p>
(這種方法會(huì)讓子組件和父組件的引用類型屬性的值同時(shí)更改)
子組件中: props:['value']
? this.value['屬性名'] = 新值 或者使用 this.$set()方法也可以
2. 子組件向父組件傳值($emit,props)
$emit
綁定一個(gè)自定義事件, 當(dāng)這個(gè)語句被執(zhí)行時(shí), 就會(huì)將參數(shù)arg傳遞給父組件,父組件通過v-on監(jiān)聽并接收參數(shù)。 通過一個(gè)例子,說明子組件如何向父組件傳遞數(shù)據(jù)。 在上個(gè)例子的基礎(chǔ)上, 點(diǎn)擊頁面渲染出來的ariticle
的item
, 父組件中顯示在數(shù)組中的下標(biāo)
// 父組件中 <template> <div class="section"> <com-article :articles="articleList" @onEmitIndex="onEmitIndex"></com-article> <p>{{currentIndex}}</p> </div> </template> <script> import comArticle from './test/article.vue' export default { name: 'HelloWorld', components: { comArticle }, data() { return { currentIndex: -1, articleList: ['紅樓夢(mèng)', '西游記', '三國(guó)演義'] } }, methods: { onEmitIndex(idx) { this.currentIndex = idx } }} </script> <template> <div> <div v-for="(item, index) in articles" :key="index" @click="emitIndex(index)">{{item}}</div> </div> </template> <script> export default { props: ['articles'], methods: { emitIndex(index) { this.$emit('onEmitIndex', index) } }} </script>
另外:props同樣可以使子組件向父組件傳值
父組件中::在子組件標(biāo)簽上綁定自定義屬性 這個(gè)屬性的值是父組件的一個(gè)函數(shù):
1.----- <child :value='fn'></child>
子組件中:
2.--------props:['value']-----接收父組件傳入的函數(shù)
this.value(要傳入父組件的值)------調(diào)用這個(gè)函數(shù) 把要傳遞的值作為形參
父組件中
3.-------- fn(接收到子組件傳入的值){
// 后續(xù)邏輯
}
二、 $children / $parent
上面這張圖片是vue
官方的解釋,通過$parent
和$children
就可以訪問組件的實(shí)例,拿到實(shí)例代表什么?代表可以訪問此組件的所有方法和data
。接下來就是怎么實(shí)現(xiàn)拿到指定組件的實(shí)例。
使用方法
// 父組件中 <template> <div class="hello_world"> <div>{{msg}}</div> <com-a></com-a> <button @click="changeA">點(diǎn)擊改變子組件值</button> </div> </template> <script> import ComA from './test/comA.vue' export default { name: 'HelloWorld', components: { ComA }, data() { return { msg: 'Welcome' } }, methods: { changeA() { // 獲取到子組件A this.$children[0].messageA = 'this is new value' } } } </script> // 子組件中 <template> <div class="com_a"> <span>{{messageA}}</span> <p>獲取父組件的值為: {{parentVal}}</p> </div> </template> <script> export default { data() { return { messageA: 'this is old' } }, computed:{ parentVal(){ return this.$parent.msg; } } } </script>
要注意邊界情況,如在#app
上拿$parent
得到的是new Vue()
的實(shí)例,在這實(shí)例上再拿$parent
得到的是undefined
,而在最底層的子組件拿$children
是個(gè)空數(shù)組。也要注意得到$parent
和$children
的值不一樣,$children
的值是數(shù)組,而$parent
是個(gè)對(duì)象
注意: 通過$children拿到的子組件的數(shù)組集合 他們的下標(biāo)是根據(jù)在父組件中子組件標(biāo)簽的書寫順序來的:
<child1> <child1 />
<child2> <child2 />
child1在child2的上面書寫 那么父組件中使用this.$children[0] 得到的就是child1
小結(jié)
上面兩種方式用于父子組件之間的通信, 而使用props進(jìn)行父子組件通信更加普遍; 二者皆不能用于非父子組件之間的通信。
三、provide/ inject
概念:
provide
/ inject
是vue2.2.0
新增的api, 簡(jiǎn)單來說就是父組件中通過provide
來提供變量, 然后再子組件中通過inject
來注入變量。
注意: 這里不論子組件嵌套有多深, 只要調(diào)用了inject
那么就可以注入provide
中的數(shù)據(jù),而不局限于只能從當(dāng)前父組件的props屬性中回去數(shù)據(jù)
舉例驗(yàn)證
接下來就用一個(gè)例子來驗(yàn)證上面的描述: 假設(shè)有三個(gè)組件: A.vue、B.vue、C.vue 其中 C是B的子組件,B是A的子組件
// A.vue <template> <div> <comB></comB> </div> </template> <script> import comB from '../components/test/comB.vue' export default { name: "A", provide: { for: "demo" }, components:{ comB } } </script> // B.vue <template> <div> {{demo}} <comC></comC> </div> </template> <script> import comC from '../components/test/comC.vue' export default { name: "B", inject: ['for'], data() { return { demo: this.for } }, components: { comC } } </script> // C.vue <template> <div> {{demo}} </div> </template> <script> export default { name: "C", inject: ['for'], data() { return { demo: this.for } } } </script>
四、ref / refs
ref
:如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向組件實(shí)例,可以通過實(shí)例直接調(diào)用組件的方法或訪問數(shù)據(jù), 我們看一個(gè)ref
來訪問組件的例子:
// 子組件 A.vue export default { data () { return { name: 'Vue.js' } }, methods: { sayHello () { console.log('hello') } } } // 父組件 app.vue <template> <component-a ref="comA"></component-a> </template> <script> export default { mounted () { const comA = this.$refs.comA; console.log(comA.name); // Vue.js comA.sayHello(); // hello } } </script>
五、eventBus
eventBus
又稱為事件總線,在vue中可以使用它來作為溝通橋梁的概念, 就像是所有組件共用相同的事件中心,可以向該中心注冊(cè)發(fā)送事件或接收事件, 所以組件都可以通知其他組件。
步驟:
1. 初始化
方式1:
首先需要?jiǎng)?chuàng)建一個(gè)事件總線并將其導(dǎo)出, 以便其他模塊可以使用或者監(jiān)聽它.
// event-bus.js import Vue from 'vue' export const EventBus = new Vue()
方式2:
// main.js Vue.prototype.$bus=new Vue() // 在Vue的原型上掛載事件總線 // 這種方式在使用事件總線的時(shí)候不需要在每個(gè)組件中導(dǎo)入bus, // 使用this.$bus.emit('自定義事件1',要傳入的值)傳值 // 使用this.$bus.$on('自定義事件1',(val)=>{})接收 val是傳入的值
2. 發(fā)送事件
假設(shè)你有兩個(gè)組件: additionNum
和 showNum
, 這兩個(gè)組件可以是兄弟組件也可以是父子組件;這里我們以兄弟組件為例:
<template> <div> <show-num-com></show-num-com> <addition-num-com></addition-num-com> </div> </template> <script> import showNumCom from './showNum.vue' import additionNumCom from './additionNum.vue' export default { components: { showNumCom, additionNumCom } } </script> // addtionNum.vue 中發(fā)送事件 <template> <div> <button @click="additionHandle">+加法器</button> </div> </template> <script> import {EventBus} from './event-bus.js' console.log(EventBus) export default { data(){ return{ num:1 } }, methods:{ additionHandle(){ EventBus.$emit('addition', { num:this.num++ }) } } } </script>
3. 接收事件
// showNum.vue 中接收事件 <template> <div>計(jì)算和: {{count}}</div> </template> <script> import { EventBus } from './event-bus.js' export default { data() { return { count: 0 } }, mounted() { EventBus.$on('addition', param => { this.count = this.count + param.num; }) } } </script>
4. 移除事件監(jiān)聽者
如果想移除事件的監(jiān)聽, 可以像下面這樣操作:
import { eventBus } from 'event-bus.js' EventBus.$off('addition', {})
事件總線的兩個(gè)問題:
- 問題1: 為什么第一次觸發(fā)的時(shí)候頁面B中的on事件沒有被觸發(fā)
- 問題2: 為什么后面再一次依次去觸發(fā)的時(shí)候會(huì)出現(xiàn),每一次都會(huì)發(fā)現(xiàn)好像之前的on事件分發(fā)都沒有被撤銷一樣,導(dǎo)致每一次的事件觸發(fā)執(zhí)行越來越多。
問題一
? 第一次觸發(fā)的時(shí)候頁面B中的on事件沒有被觸發(fā)
產(chǎn)生原因
當(dāng)我們還在頁面A的時(shí)候,頁面B還沒生成,也就是頁面B中的 created中所監(jiān)聽的來自于A中的事件還沒有被觸發(fā)。這個(gè)時(shí)候當(dāng)你A中emit事件的時(shí)候,B其實(shí)是沒有監(jiān)聽到的。
解決辦法
我們可以把A頁面組件中的emit事件寫在beforeDestory中去。因?yàn)檫@個(gè)時(shí)候,B頁面組件已經(jīng)被created了,也就是我們寫的on事件已經(jīng)觸發(fā)了,所以可以在beforeDestory的時(shí)候, on事件已經(jīng)觸發(fā)了,所以可以在beforeDestory的時(shí)候,on事件已經(jīng)觸發(fā)了,所以可以在beforeDestory的時(shí)候,emit事件
問題二
? 后面再一次依次去觸發(fā)的時(shí)候會(huì)出現(xiàn),每一次都會(huì)發(fā)現(xiàn)好像之前的on事件分發(fā)都沒有被撤銷一樣,導(dǎo)致每一次的事件觸發(fā)執(zhí)行越來越多。
產(chǎn)生原因
就是說,這個(gè)$on事件是不會(huì)自動(dòng)清楚銷毀的,需要我們手動(dòng)來銷毀。(不過我不太清楚這里的external bus 是什么意思,有大神能解答一下的嗎,尤大大也提到如果是注冊(cè)的是external bus 的時(shí)候需要清除)
解決辦法
在B組件頁面中添加Bus.$off來關(guān)閉
// 在B組件頁面中添加以下語句,在組件beforeDestory的時(shí)候銷毀。 beforeDestroy () { bus.$off('get', this.myhandle) },
小結(jié)
所以,如果想要用 bus 來進(jìn)行頁面組件之間的數(shù)據(jù)傳遞,需要注意兩點(diǎn):
一、組件A emit 事件應(yīng)在beforeDestory生命周期內(nèi)。
二、組件B內(nèi)的 on 記得要銷毀
六、Vuex
1. Vuex介紹
Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲(chǔ)管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測(cè)的方式發(fā)生變化. Vuex 解決了多個(gè)視圖依賴于同一狀態(tài)
和來自不同視圖的行為需要變更同一狀態(tài)
的問題,將開發(fā)者的精力聚焦于數(shù)據(jù)的更新而不是數(shù)據(jù)在組件之間的傳遞上
2. Vuex各個(gè)模塊
state
:用于數(shù)據(jù)的存儲(chǔ),是store中的唯一數(shù)據(jù)源getters
:如vue中的計(jì)算屬性一樣,基于state數(shù)據(jù)的二次包裝,常用于數(shù)據(jù)的篩選和多個(gè)數(shù)據(jù)的相關(guān)性計(jì)算mutations
:類似函數(shù),改變state數(shù)據(jù)的唯一途徑,且不能用于處理異步事件actions
:類似于mutation
,用于提交mutation
來改變狀態(tài),而不直接變更狀態(tài),可以包含任意異步操作modules
:類似于命名空間,用于項(xiàng)目中將各個(gè)模塊的狀態(tài)分開定義和操作,便于維護(hù)
3. Vuex實(shí)例應(yīng)用
// 父組件 <template> <div id="app"> <ChildA/> <ChildB/> </div> </template> <script> import ChildA from './components/ChildA' // 導(dǎo)入A組件 import ChildB from './components/ChildB' // 導(dǎo)入B組件 export default { name: 'App', components: {ChildA, ChildB} // 注冊(cè)A、B組件 } </script> // 子組件childA <template> <div id="childA"> <h1>我是A組件</h1> <button @click="transform">點(diǎn)我讓B組件接收到數(shù)據(jù)</button> <p>因?yàn)槟泓c(diǎn)了B,所以我的信息發(fā)生了變化:{{BMessage}}</p> </div> </template> <script> export default { data() { return { AMessage: 'Hello,B組件,我是A組件' } }, computed: { BMessage() { // 這里存儲(chǔ)從store里獲取的B組件的數(shù)據(jù) return this.$store.state.BMsg } }, methods: { transform() { // 觸發(fā)receiveAMsg,將A組件的數(shù)據(jù)存放到store里去 this.$store.commit('receiveAMsg', { AMsg: this.AMessage }) } } } </script> // 子組件 childB <template> <div id="childB"> <h1>我是B組件</h1> <button @click="transform">點(diǎn)我讓A組件接收到數(shù)據(jù)</button> <p>因?yàn)槟泓c(diǎn)了A,所以我的信息發(fā)生了變化:{{AMessage}}</p> </div> </template> <script> export default { data() { return { BMessage: 'Hello,A組件,我是B組件' } }, computed: { AMessage() { // 這里存儲(chǔ)從store里獲取的A組件的數(shù)據(jù) return this.$store.state.AMsg } }, methods: { transform() { // 觸發(fā)receiveBMsg,將B組件的數(shù)據(jù)存放到store里去 this.$store.commit('receiveBMsg', { BMsg: this.BMessage }) } } } </script>
vuex的store,js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { // 初始化A和B組件的數(shù)據(jù),等待獲取 AMsg: '', BMsg: '' } const mutations = { receiveAMsg(state, payload) { // 將A組件的數(shù)據(jù)存放于state state.AMsg = payload.AMsg }, receiveBMsg(state, payload) { // 將B組件的數(shù)據(jù)存放于state state.BMsg = payload.BMsg } } export default new Vuex.Store({ state, mutations })
七、vue slot 插槽通信
父子插槽通信
可以理解為在定義組件的時(shí)候預(yù)先留好了一個(gè)插槽,父組件在調(diào)用子組件的使用將東西插到插槽里面顯示,或者說從外向里讀。
//父組件 <div> <h3>父組件</h3> <testChild> <div>默認(rèn)插槽</div> </testChild> </div> //子組件 testChild <div> <h4>子組件</h4> <slot></slot> //default slot </div>
結(jié)果如下
父組件
子組件
默認(rèn)插槽
父向子通信
其實(shí)就是讀取父里面data的內(nèi)容
/* 父組件 * list: [ * {name: "aaa"}, {name: "bbb"} * ] */ <div> <h3>父組件</h3> <testChild> <template v-slot:test>//v-slot: + 插槽名 v-slot:default 也是允許的 <ul> <li v-for="item in list">{{item.name}}</li> </ul> </template> </testChild> </div> //子組件 textChild <div> <h4>子組件</h4> <slot name="test"></slot> //name="插槽名" </div>
結(jié)果如下
父組件
子組件
aaa
bbb
子向父通信
父組件無法直接訪問子組件里面的變量
//父組件 <div> <h3>父組件</h3> <testChild> <template v-slot:test="data">//具名插槽,v-slot: +插槽名+ ="自定義數(shù)據(jù)名",子組件所傳參數(shù)都是其屬性 <ul> <li v-for="item in data.list2">{{item.name}}</li> </ul> </template> <template v-slot="dataDefalut">//默認(rèn)插槽 {{dataDefalut.sName}} </template> </testChild> </div> //子組件 <template> <div> <h4>子組件</h4> <slot name="test" :list2="list2"></slot> <slot :sName="name"></slot> </div> </template>
以上就是vue組件通信方式有哪些?的詳細(xì)內(nèi)容,更多關(guān)于vue組件通信的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
axios+Vue實(shí)現(xiàn)上傳文件顯示進(jìn)度功能
這篇文章主要介紹了axios+Vue上傳文件顯示進(jìn)度效果,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04vue中使用element ui的彈窗與echarts之間的問題詳解
這篇文章主要介紹了vue中使用element ui的彈窗與echarts之間的問題詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10解決Vue控制臺(tái)報(bào)錯(cuò)Failed to mount component: tem
這篇文章主要介紹了解決Vue控制臺(tái)報(bào)錯(cuò)Failed to mount component: template or render function not defined.問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06如何使用vue-pdf-embed實(shí)現(xiàn)PDF在線預(yù)覽
vue-pdf-embed是一個(gè)基于Vue.js的插件,專門用于在Vue應(yīng)用中嵌入和展示PDF文件,本文將使用vue-pdf-embed實(shí)現(xiàn)PDF在線預(yù)覽功能,有需要的小伙伴可以參考一下2025-03-03vue+Element實(shí)現(xiàn)登錄隨機(jī)驗(yàn)證碼
這篇文章主要為大家詳細(xì)介紹了vue+Element實(shí)現(xiàn)登錄隨機(jī)驗(yàn)證碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04vue計(jì)算屬性computed、事件、監(jiān)聽器watch的使用講解
今天小編就為大家分享一篇關(guān)于vue計(jì)算屬性computed、事件、監(jiān)聽器watch的使用講解,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01vite?vue3?規(guī)范化與Git?Hooks詳解
這篇文章主要介紹了vite?vue3?規(guī)范化與Git?Hooks,本文重點(diǎn)討論?git?提交規(guī)范,結(jié)合示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-10-10