VUE之组件通信(三)
1、$refs与$parent
1)概述:
- $refs用于:父——>子。
- $parent用于:子——>父。
2)原理如下:
属性 | 说明 |
$refs | 值为对象,包含所有被ref属性标识的DOM元素或组件实例。 |
$parent | 值为对象,当前组件的父组件实例对象 |
$refs 包含所有子组件的实例对象
<template><div class="father"><h3>父组件</h3><h4>房产:{{house}}</h4><button @click="changeToy">修改Child1的玩具</button><button @click="changeComputer">修改Child2的电脑</button><button @click="getAllChild($refs)">获取所有子组件的实例对象</button><Child1 ref="c1"/><Child2 ref="c2" /></div>
</template><script setup lang="ts" name="Father">import Child1 from './Child1.vue'import Child2 from './Child2.vue'import {ref} from "vue"let c1 = ref()let c2 = ref()// 数据let house = ref(4)// 方法function changeToy(){console.log(c1.value)c1.value.toy = '小猪佩奇'}function changeComputer(){c1.value.computer= '华为'}function getAllChild([refs:any}){for(let key in refs){console.log(refs[key])refs[key]+=3}}// 向外部提供数据defineExpose({house})</script>
<template><div class="child1"><h3>子组件1</h3><h4>玩具:{{toy}} 个</h4><h4>书籍:{{book}} 本</h4><button @click="minusHouse($parent)">干掉父亲的一套房产</button></div>
</template><script setup lang="ts" name="Child1">import {ref} from "vue"//数据let toy = ref('奥特曼')let book = ref(3)//方法function minusHouse(parent:any){console.log(parent)parent.house -= 1}// 把数据交给外部defineExpose({toy,book})</script>
<template><div class="child2"><h3>子组件2</h3><h4>电脑:{{computer}}</h4><h4>书籍:{{book}} 本</h4></div>
</template><script setup lang="ts" name="Child2">import {ref} from "vue"//数据let computer= ref('奥特曼')let book = ref(6)// 把数据交给外部defineExpose({computer,book})
</script>
一个注意点,有时候.value,有时候不需要:
let obj = reactive({ a:1,b:2,c:ref(3)}) let x = ref(4)
console.log(obj.a) console.log(obj.b) console.log(obj.c)//自动解包
console.log(x.value)
2、provide-inject
<template><div class="father"><h3>父组件2</h3><h4>银子:{{money}}万元</h4><h4>车子:一辆{{car.brand}}车,价值{{car.price}}万元</h4><Child/></div>
</template><script setup lang="ts" name="Child2">import Child from './Child.vue'import {ref,reactive,provide} from "vue"let money = ref(100)let car = reactive({brand:'奔驰',price:100})function updateMoney(value){money.value -= value}// 向后代提供数据provide('qian',{money,updateMoney})provide('che',car)
</script>
<template><div class="grand-child"><h3>我是孙组件</h3><h4>银子:{{x}}</h4><h4>车子:一辆{{car.brand}}车,价值{{car.price}}万元</h4><button @click="updateMoney(6)">花爷爷的钱</button></div>
</template><script setup lang="ts" name="GrandChild">import {inject} from 'vue'let {money,updateMoney} = inject('qian',{money:0,updateMoney:(x:number)=>{}})let car= inject('che',{brand:'未知',price:0}) //通过默认值隐慧教推断</script>