Vue組件高級通訊之$children與$parent
一、$children組件屬性
官方介紹:當前實例的直接子組件。需要注意 $children 并不保證順序
,也不是響應(yīng)式的。
即$children是組件自帶的屬性,它可以獲取到當前組件的子組件,并以數(shù)組的形式返回。
二、$parent
官方介紹:指定已創(chuàng)建的實例之父實例,在兩者之間建立父子關(guān)系。子實例可以用 this.$parent 訪問父實例
,子實例被推入父實例的 $children 數(shù)組中。
如果組件沒有父組件,他的$parent為undefined
,App組件(根組件)的$parent不是undefined,也不是App本身。
如果組件有多個父親,但是$parent只能找到一個,不知道是不是bug,建議慎用。
注意:節(jié)制地使用$parent 和 $children
它們的主要目的是作為訪問組件的應(yīng)急方法。更推薦用 props 和 events 實現(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的詳細內(nèi)容,更多關(guān)于Vue組件通訊$children $parent的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue3使用postcss-px-to-viewport實現(xiàn)頁面自適應(yīng)
postcss-px-to-viewport 是一個 PostCSS 插件,它可以將 px 單位轉(zhuǎn)換為視口單位,下面我們就看看如何使用postcss-px-to-viewport實現(xiàn)頁面自適應(yīng)吧2024-01-01解決antd 表單設(shè)置默認值initialValue后驗證失效的問題
這篇文章主要介紹了解決antd 表單設(shè)置默認值initialValue后驗證失效的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11vue如何實現(xiàn)清空this.$route.query的值
這篇文章主要介紹了vue如何實現(xiàn)清空this.$route.query的值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09vue3中利用Export2Excel將數(shù)據(jù)導(dǎo)出為excel表格
這篇文章主要給大家介紹了關(guān)于vue3中利用Export2Excel將數(shù)據(jù)導(dǎo)出為excel表格的相關(guān)資料,最近項目需要前端來導(dǎo)出Excel操作,所以給大家總結(jié)下,需要的朋友可以參考下2023-09-09