ref :可以获取到某一个组件,子组件
$children :组件实例的属性,可以获取到当前组件的全部子组件【数组】
$parent:组件实例的属性,可以获取到当前子组件的父组件,进而可以操作父组件的数据和方法
父组件:
<template>
<div>
<h2>爸爸有存款:{{money}}</h2>
<button @click="JieQianFromXM(100)">找小明借钱100</button><br><br>
<button @click="JieQianFromXH(150)">找小红借钱150</button><br><br>
<button @click="JieQianFromAll(200)">找所有孩子借200</button><br><br>
<!--ref : 获取节点(组件标签)-->
<!--在vue组件中可以通过ref获取子组件,就可以进行操作子组件的数据与方法-->
<Son ref="xm"></Son>
<Daughter ref="xh"></Daughter>
</div>
</template>
<script>
import Son from "@/views/communication/ChildrenParentTest/Son.vue";
import Daughter from "@/views/communication/ChildrenParentTest/Daughter.vue";
export default {
name: "ChildrenParentTest",
components:{Son,Daughter},
data(){
return{
money:1000
}
},
methods:{
//找儿子借钱
JieQianFromXM(money){
this.money += money
// console.log(this.$refs.xm)
// ref可以获取到真实的DOM节点,当然也可以获取子组件标签(操作子组件数据和方法)
this.$refs.xm.money -= money
},
//找女儿借钱
JieQianFromXH(money){
this.money += money
this.$refs.xh.money -= money
},
// 找所以孩子借钱
JieQianFromAll(money){
this.money += 2*money
// 组件实例自身拥有一个属性$children,可以获取到当前组件当中 全部子组件
// console.log(this.$children)
this.$children.forEach(item=>{
item.money -= money
})
//切记别这样写,如果子组件过多,第0项可能不是小明
// this.$children[0].money -= money
// this.$children[1].money -= money
}
}
}
</script>
子组件1:
<template>
<div>
<h2>儿子有存款:{{money}}</h2>
<button @click="giveMoney(50)">给爸爸钱:50</button>
</div>
</template>
<script>
export default {
name: "Son",
data(){
return{
money:10000
}
},
methods:{
giveMoney(money){
// 儿子-50
this.money -= money
//需要在子组件内部,获取到父组件,让父组件的数据加上50
//可以通过parent属性获取到某一个组件父组件,可以操作父组件的数据和方法
//父亲+50
this.$parent.money += money
}
}
}
</script>
子组件2:
<template>
<div>
<h2>女儿有存款:{{ money }}</h2>
<button @click="giveMoney(100)">给爸爸钱100</button>
</div>
</template>
<script>
export default {
name: "Daughter",
data() {
return {
money: 20000
}
},
methods: {
giveMoney(money) {
// 女儿 -100
this.money -= money
// 父亲 +100
this.$parent.money += money
}
}
}
</script>