詳解vue2.0組件通信各種情況總結(jié)與實(shí)例分析
Props在vue組件中各種角色總結(jié)
在Vue中組件是實(shí)現(xiàn)模塊化開發(fā)的主要內(nèi)容,而組件的通信更是vue數(shù)據(jù)驅(qū)動的靈魂,現(xiàn)就四種主要情況總結(jié)如下:
使用props傳遞數(shù)據(jù)---組件內(nèi)部
//html
<div id="app1">
<i>注意命名規(guī)定:僅在html內(nèi)使用my-message</i>
<child my-message="組件內(nèi)部數(shù)據(jù)傳遞"></child>
</div>
//js
<script>
Vue.component('child', {
props: ['myMessage'],
template: '<mark>{{ myMessage }}<mark/>'
});
new Vue({
el: '#app1'
})
</script>
動態(tài)props通信---組件與根節(jié)點(diǎn)(父子之間)
<div id="app2">
<input v-model="parentMsg">
<br>
<child :parent-msg="parentMsg"></child>
</div>
<script>
Vue.component('child', {
props: ['parentMsg'],
template: '<mark>{{ parentMsg }}<mark/>'
});
new Vue({
el: '#app2',
data: {
parentMsg: 'msg from parent!'
}
})
</script>
對比分析:
例子1:
<comp some-prop="1"></comp> //組件內(nèi)部數(shù)據(jù)傳遞,對應(yīng)字面量語法:傳遞了一個字符串"1"
例子2:
<comp v-bind:some-prop="1"></comp> //組件與根節(jié)點(diǎn)數(shù)據(jù)傳遞,對應(yīng)動態(tài)語法:傳遞實(shí)際的數(shù)字:js表達(dá)式
單向數(shù)據(jù)流動特點(diǎn):父組件屬性變化時將傳導(dǎo)給子組件,反之不可
兩種改變prop情況
注意在 JavaScript 中對象和數(shù)組是引用類型,指向同一個內(nèi)存空間,如果 prop 是一個對象或數(shù)組,在子組件內(nèi)部改變它會影響父組件的狀態(tài)。
//定義一個局部data屬性,并將 prop 的初始值作為局部數(shù)據(jù)的初始值
props: ['initialCounter'],
data: function () {
return { counter: this.initialCounter }
}
//定義一個局部computed屬性,此屬性從 prop 的值計算得出
props: ['size'],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}
子組件索引
盡管有 props 和 events ,但是有時仍然需要在 JavaScript 中直接訪問子組件。為此可以使用 ref 為子組件指定一個索引 ID
<div id="parent">
<!-- vm.$refs.p will be the DOM node -->
<b ref="p">hello</b>
<!-- vm.$refs.child will be the child comp instance -->
<user-profile v-for='i in 3' ref="profile"></user-profile>
</div>
<script>
var userPf=Vue.component('user-profile',{
template:'<div>hello $refs</div>'
});
var parent = new Vue({ el: '#parent' });
// 訪問子組件
var child = parent.$refs.profile;
console.log(child[0]);
console.log(parent.$refs.p);
</script>
$refs 只在組件渲染完成后才填充,并且它是非響應(yīng)式的。它僅僅作為一個直接訪問子組件的應(yīng)急方案——應(yīng)當(dāng)避免在模版或計算屬性中使用 $refs 。
數(shù)據(jù)反傳---自定義事件
自定義事件的根基在于每個vue實(shí)例都實(shí)現(xiàn)了事件接口(Event interface)
Vue的事件系統(tǒng)分離自瀏覽器的EventTarget API。盡管它們的運(yùn)行類似,但是$on 和 $emit 不是addEventListener 和 dispatchEvent 的別名。
父組件可以在使用子組件的地方直接用 v-on 來監(jiān)聽子組件觸發(fā)的事件
- 監(jiān)聽:$on(eventName)
- 觸發(fā):$emit(eventName)
<div id="app3">
<p>Look at the parent's data: <mark>{{t}}</mark> & the child's data: <mark>{{childWords}}</mark></p>
<child v-on:add="pChange"></child>
<child v-on:add="pChange"></child>
<child v-on:click.native="native"></child>
</div>
<script>
Vue.component('child', {
template: `<button @click="add">{{ c }}</button>`,
data: function () {
return {
c: 0,
msg: 'I am from child\'s data'
}
},
methods: {
add: function () {
this.c += 1;
this.$emit('add',this.msg);
}
},
});
new Vue({
el: '#app3',
data: {
t: 0,
childWords: ''
},
methods: {
pChange: function (msg) {
this.t += 1;
this.childWords=msg;
},
native:function () {
alert('I am a native event ,which comes from the root element!');
}
}
})
</script>
兄弟間通信---簡單場景用bus,復(fù)雜場景用vuex
<div id="app4">
<display></display>
<increment></increment>
</div>
<script>
var bus = new Vue();
Vue.component('increment', {
template: `<button @click="add">+</button>`,
data: function () {
return {count: 0}
},
methods: {
add: function () {
bus.$emit('inc', this.count+=1)
}
}
});
Vue.component('display', {
template: `<span>Clicked: <mark>{{c}}</mark> times</span>`,
data: function () {
return {c: 0}
},
created: function () {
var self=this;
// bus.$on('inc', function (num) {
// self.c = num
// });
bus.$on('inc', (num) =>
this.c = num
);
}
});
vm = new Vue({
el: "#app4",
})
</script>
總結(jié):Vue中關(guān)于組件間及組件與根節(jié)點(diǎn)間通信都可以人為是父子兄弟間的通信,另外父子關(guān)系是相對的即與上下文有關(guān)(比如A組件的父組件可能是B組件的子組件);上述四個例子分別演示了不同組件通信的機(jī)制。
澄清了上述問題不難理這句話:
編譯作用域---父組件模板的內(nèi)容在父組件作用域內(nèi)編譯;子組件模板的內(nèi)容在子組件作用域內(nèi)編譯。分發(fā)內(nèi)容是在父組件作用域內(nèi)編譯
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解vue中在循環(huán)中使用@mouseenter 和 @mouseleave事件閃爍問題解決方法
這篇文章主要介紹了詳解vue中在循環(huán)中使用@mouseenter 和 @mouseleave事件閃爍問題解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
vue項(xiàng)目netWork地址無法訪問的問題及解決
這篇文章主要介紹了vue項(xiàng)目netWork地址無法訪問的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
Taro+vue3?實(shí)現(xiàn)電影切換列表功能
我們做類似于貓眼電影的小程序或者H5?的時候?我們會做到那種?左右滑動的電影列表,這種列表一般帶有電影場次,我這個項(xiàng)目是基于Taro?+vue3?+ts?來寫的用的組件庫也是京東的nut-ui以上的代碼和組件也有的是我二次封裝的組件,對vue3電影切換列表知識,感興趣的朋友一起看看吧2024-01-01
解決Vue+Electron下Vuex的Dispatch沒有效果問題
這篇文章主要介紹了Vue+Electron下Vuex的Dispatch沒有效果的解決方案 ,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05

