-
概述:
-
$refs
用于 :父→子。 -
$parent
用于:子→父。
-
- 原理如下:
属性 | 说明 |
---|---|
$refs | 值为对象,包含所有被ref 属性标识的DOM 元素或组件实例。 |
$parent | 值为对象,当前组件的父组件实例对象。 |
child1组件
<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'
const toy = ref('奥特曼')
const book = ref(3)
const minusHouse = (parent) => {parent.house--
}
// 把数据交给外部
defineExpose({ toy, book })
</script><style scoped>
.child1 {background-color: rgb(173, 148, 232);height: 100px;margin: 10px 0;
}
</style>
child2组件:
<template><div class="child2"><h3>子组件2</h3><h4>手机:{{ phone }}</h4><h4>书本:{{ book }}本</h4></div>
</template><script setup lang="ts" name="Child2">
import { ref } from 'vue'
const phone = ref('oppo')
const book = ref(6)
// 把数据交给外部
defineExpose({ phone, book })
</script>
<style scoped>
.child2 {background-color: aquamarine;height: 80px;
}
</style>
father组件:
<template><div class="father"><h3>父组件</h3><h4>房产:{{ house }}</h4><button @click="changeToy()">修改child1的玩具</button><button @click="changePhone()">修改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'
const c1 = ref()
const c2 = ref()
const house = ref(6)
// 把数据交给外部
defineExpose({house})
const changeToy = () => {c1.value.toy = '小猪佩奇'
}
const changePhone = () => {c2.value.phone = '华为'
}
const getAllChild = (refs: any) => {console.log(refs)for (let key in refs) {refs[key].book += 3}
}
</script>
<style scoped>
.father {background-color: pink;width: 200px;height: 400px;padding: 20px;
}button {margin: 5px 0;
}
</style>