ref可以获取真实的dom节点,可以获取到子组件实例VC
$parent可以再子组件内部获取到父组件的实例
父组件中使用子组件时给子组件绑定ref
<template>
<div class="box">
ref与$parent
<div>父组件:{{ money }}</div>
<button @click="handeler">点击改变数值</button>
<Son ref="son"></Son>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import Son from "./Son.vue";
const money = ref(1000);
let son = ref();
console.log(son.value);
const handeler = () => {
money.value += 10;
son.value.money -= 10;
console.log(son.value.money);
};
</script>
组件内部数据对外是关闭状态
如果想让外部访问需要通过defineExpose方法对外暴露
子组件中
<template>
<div class="son">子组件{{ money }}</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const money = ref(2000);
defineExpose({
money,
});
</script>
子组件中获取父组件的方法和数据使用$parent
在父组件中通过defineExpose把数据暴露出来,在子组件中使用时用$parent
<template>
<div class="dau">
<div>{{ money }}</div>
<button @click="handeler($parent)">点击改变数值</button>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const money = ref(200);
const handeler = ($parent) => {
console.log($parent.money);
money.value += 1;
$parent.money -= 1;
};
</script>