$refs
用于 父传子
值为对象,包含所有被ref
属性标识的DOM
元素或组件实例。
1<template>
2 <h2>父组件</h2>
3 <button @click="change">修改子组件数据</button>
4 <button @click="getAllComp($refs)">获取所有子组件实例对象</button>
5 <hr/>
6 <child-comp ref="cc"/>
7 <brother-comp ref="bc"/>
8
9</template>
10
11<script lang="ts" name="ParentComp" setup>
12import ChildComp from "@/components/ChildComp.vue";
13import BrotherComp from "@/components/BrotherComp.vue";
14import {ref} from "vue";
15
16let cc = ref()
17let bc = ref()
18
19function change() {
20 cc.value.num -= 1
21 bc.value.num += 1
22}
23
24function getAllComp(refs:{[key:string]:any}) {
25 for (let key in refs) {
26 console.log(refs[key])
27 }
28}
29
30</script>
1<template>
2 <h2>子组件</h2>
3 {{ num }}
4 <hr/>
5</template>
6
7<script lang="ts" name="ChildComp" setup>
8import {ref} from "vue";
9
10let num = ref(10)
11defineExpose({num})
12</script>
1<template>
2 <h2>兄弟组件</h2>
3 {{ num}}
4</template>
5
6<script lang="ts" name="BrotherComp" setup>
7import {ref} from "vue";
8
9let num = ref(10)
10defineExpose({num})
11</script>
:::