Vue組件高級通訊之$children與$parent
一、$children組件屬性
官方介紹:當前實例的直接子組件。需要注意 $children 并不保證順序,也不是響應式的。
即$children是組件自帶的屬性,它可以獲取到當前組件的子組件,并以數組的形式返回。
二、$parent
官方介紹:指定已創(chuàng)建的實例之父實例,在兩者之間建立父子關系。子實例可以用 this.$parent 訪問父實例,子實例被推入父實例的 $children 數組中。
如果組件沒有父組件,他的$parent為undefined,App組件(根組件)的$parent不是undefined,也不是App本身。
如果組件有多個父親,但是$parent只能找到一個,不知道是不是bug,建議慎用。
注意:節(jié)制地使用$parent 和 $children它們的主要目的是作為訪問組件的應急方法。更推薦用 props 和 events 實現父子組件通信。
三、小例子:通過借錢案例加深理解
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的詳細內容,更多關于Vue組件通訊$children $parent的資料請關注腳本之家其它相關文章!
相關文章
vue插件開發(fā)之使用pdf.js實現手機端在線預覽pdf文檔的方法
這篇文章主要介紹了vue插件開發(fā)之使用pdf.js實現手機端在線預覽pdf文檔的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
Vue中的Object.defineProperty全面理解
這篇文章主要介紹了Vue中的Object.defineProperty全面理解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
vuex+axios+element-ui實現頁面請求loading操作示例
這篇文章主要介紹了vuex+axios+element-ui實現頁面請求loading操作,結合實例形式分析了vuex+axios+element-ui實現頁面請求過程中l(wèi)oading遮罩層相關操作技巧與使用注意事項,需要的朋友可以參考下2020-02-02

