您好,登錄后才能下訂單哦!
前言
眾所周知vue是一種mvvm框架,它相對(duì)于jquery可能比較大的差異點(diǎn)之一就在于組件之間的通信了。本文重點(diǎn)是梳理了前兩個(gè),父子組件通信和eventBus通信,我覺得Vue文檔里的說(shuō)明還是有一些簡(jiǎn)易,我自己第一遍是沒(méi)看明白。
第一種通信方式:父子組件通信
父組件向子組件傳遞數(shù)據(jù)
父組件一共需要做4件事
1.import son from './son.js'
引入子組件 son
2.在components : {"son"}
里注冊(cè)所有子組件名稱
3.在父組件的template應(yīng)用子組件, <son></son>
4.如果需要傳遞數(shù)據(jù)給子組件,就在template模板里寫 <son :num="number"></son>
// 1.引入子組件 import counter from './counter' import son from './son'
// 2.在ccmponents里注冊(cè)子組件 components : { counter, son },
// 3.在template里使用子組件 <son></son>
// 4.如果需要傳遞數(shù)據(jù),也是在templete里寫 <counter :num="number"></counter>
子組件只需要做1件事
1.用props接受數(shù)據(jù),就可以直接使用數(shù)據(jù)
2.子組件接受到的數(shù)據(jù),不能去修改。如果你的確需要修改,可以用計(jì)算屬性,或者把數(shù)據(jù)賦值給子組件data里的一個(gè)變量
// 1.用Props接受數(shù)據(jù) props: [ 'num' ],
// 2.如果需要修改得到的數(shù)據(jù),可以這樣寫 props: [ 'num' ], data () { return { number : this.num } },
子組件向父組件傳遞數(shù)據(jù)
父組件一共需要做2件事情
在template里定義事件
在methods里寫函數(shù),監(jiān)聽子組件的事件觸發(fā)
// 1. 在templete里應(yīng)用子組件時(shí),定義事件changeNumber <counter :num="number" @changeNumber="changeNumber" > </counter>
// 2. 用changeNumber監(jiān)聽事件是否觸發(fā) methods: { changeNumber(e){ console.log('子組件emit了',e); this.number = e }, }
子組件一共需要1件事情
在數(shù)據(jù)變化后,用$emit觸發(fā)即可
// 1. 子組件在數(shù)據(jù)變化后,用$emit觸發(fā)即可,第二個(gè)參數(shù)可以傳遞參數(shù) methods: { increment(){ this.number++ this.$emit('changeNumber', this.number) }, }
第二種通信方式: eventBus
eventBus這種通信方式,針對(duì)的是非父子組件之間的通信,它的原理還是通過(guò)事件的觸發(fā)和監(jiān)聽。
但是因?yàn)槭欠歉缸咏M件的關(guān)系,他們需要有一個(gè)中間組件來(lái)連接。
我是使用的通過(guò)在根組件,也就是#app組件上定義了一個(gè)所有組件都可以訪問(wèn)到的組件,具體使用方式如下
使用eventBus傳遞數(shù)據(jù),我們一共需要做3件事情
1.給app組件添加Bus屬性 (這樣所有組件都可以通過(guò)this.$root.Bus
訪問(wèn)到它,而且不需要引入任何文件)
2.在組件1里,this.$root.Bus.$emit
觸發(fā)事件
3.在組件2里,this.$root.Bus.$on
監(jiān)聽事件
// 1.在main.js里給app組件,添加bus屬性 import Vue from 'vue' new Vue({ el: '#app', components: { App }, template: '<App/>', data(){ return { Bus : new Vue() } } })
// 2.在組件1里,觸發(fā)emit increment(){ this.number++ this.$root.Bus.$emit('eventName', this.number) },
// 3.在組件2里,監(jiān)聽事件,接受數(shù)據(jù) mounted(){ this.$root.Bus.$on('eventName', value => { this.number = value console.log('busEvent'); }) },
第三種通信方式: 利用localStorage或者sessionStorage
這種通信比較簡(jiǎn)單,缺點(diǎn)是數(shù)據(jù)和狀態(tài)比較混亂,不太容易維護(hù)。
通過(guò)window.localStorage.getItem(key)
獲取數(shù)據(jù)
通過(guò)window.localStorage.setItem(key,value)
存儲(chǔ)數(shù)據(jù)
注意:用JSON.parse() / JSON.stringify()
做數(shù)據(jù)格式轉(zhuǎn)換。
第四種通信方式: 利用Vuex
Vuex比較復(fù)雜,可以單獨(dú)寫一篇
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。