Vue組件高級通訊之$children與$parent
一、$children組件屬性
官方介紹:當(dāng)前實(shí)例的直接子組件。需要注意 $children 并不保證順序,也不是響應(yīng)式的。
即$children是組件自帶的屬性,它可以獲取到當(dāng)前組件的子組件,并以數(shù)組的形式返回。
二、$parent
官方介紹:指定已創(chuàng)建的實(shí)例之父實(shí)例,在兩者之間建立父子關(guān)系。子實(shí)例可以用 this.$parent 訪問父實(shí)例,子實(shí)例被推入父實(shí)例的 $children 數(shù)組中。
如果組件沒有父組件,他的$parent為undefined,App組件(根組件)的$parent不是undefined,也不是App本身。
如果組件有多個(gè)父親,但是$parent只能找到一個(gè),不知道是不是bug,建議慎用。
注意:節(jié)制地使用$parent 和 $children它們的主要目的是作為訪問組件的應(yīng)急方法。更推薦用 props 和 events 實(shí)現(xiàn)父子組件通信。
三、小例子:通過借錢案例加深理解
Father.vue
<template>
<div>
<h2>父親金錢:{{ fatherMoney }}</h2>
<button @click="jieqian">問子女借錢100元</button>
<Son></Son>
<Daughter></Daughter>
</div>
</template>
<script>
import Son from "./Son";
import Daughter from "./Daughter";
export default {
components: {
Son,
Daughter,
},
data() {
return {
fatherMoney: 0,
};
},
methods: {
jieqian() {
this.fatherMoney += 100 * 2;
this.$children.forEach((dom) => {
dom.childrenMoney -= 100;
});
},
},
};
</script>
<style></style>Son
<template>
<div style="background-color: #999">
<h2>兒子金錢:{{ childrenMoney }}</h2>
<button @click="giveFatherMoney(100)">給父親100</button>
</div>
</template>
<script>
export default {
name: "Son",
data() {
return {
childrenMoney : 20000,
};
},
methods: {
giveFatherMoney(money) {
this.$parent.fatherMoney += money;
this.childrenMoney -= money;
},
},
};
</script>
<style>
</style>Daughter
<template>
<div style="background-color: #999">
<h2>女兒金錢:{{ childrenMoney }}</h2>
<button @click="giveFatherMoney(100)">給父親100</button>
</div>
</template>
<script>
export default {
name: "Daughter",
data() {
return {
childrenMoney : 20000,
};
},
methods: {
giveFatherMoney(money) {
this.$parent.fatherMoney += money;
this.childrenMoney -= money;
},
},
};
</script>
<style>
</style>以上就是Vue組件高級通訊之$children與$parent的詳細(xì)內(nèi)容,更多關(guān)于Vue組件通訊$children $parent的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue插件開發(fā)之使用pdf.js實(shí)現(xiàn)手機(jī)端在線預(yù)覽pdf文檔的方法
這篇文章主要介紹了vue插件開發(fā)之使用pdf.js實(shí)現(xiàn)手機(jī)端在線預(yù)覽pdf文檔的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07
Vue中的Object.defineProperty全面理解
這篇文章主要介紹了Vue中的Object.defineProperty全面理解,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
使用Vue3實(shí)現(xiàn)一個(gè)簡單的思維導(dǎo)圖組件
思維導(dǎo)圖是一種用于表示信息、想法和概念的圖形化工具,本文將基于 Vue3和VueDraggable實(shí)現(xiàn)一個(gè)簡單的思維導(dǎo)圖組件,支持節(jié)點(diǎn)拖拽,編輯及節(jié)點(diǎn)之間的關(guān)系連接,希望對大家有所幫助2025-04-04
vuex+axios+element-ui實(shí)現(xiàn)頁面請求loading操作示例
這篇文章主要介紹了vuex+axios+element-ui實(shí)現(xiàn)頁面請求loading操作,結(jié)合實(shí)例形式分析了vuex+axios+element-ui實(shí)現(xiàn)頁面請求過程中l(wèi)oading遮罩層相關(guān)操作技巧與使用注意事項(xiàng),需要的朋友可以參考下2020-02-02
Vue向下滾動(dòng)加載更多數(shù)據(jù)scroll案例詳解
這篇文章主要介紹了Vue向下滾動(dòng)加載更多數(shù)據(jù)scroll案例詳解,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08

