子组件
Son/index.vue
子组件的数据和方法一定要记得用defineExpose暴露,不然父组件用ref是获取不到的!!!
<script setup>
import { ref } from "vue";
const sonNum = ref(1);
const changeSon = () => {
sonNum.value++;
};
defineExpose({
sonNum,
changeSon,
});
</script>
<template>
<div class="son">
{{ sonNum }}
</div>
</template>
<style scoped lang="scss">
.son {
width: 100px;
height: 20px;
border: 1px pink solid;
}
</style>
Father/index.vue
<script setup>
import { ref, onMounted, watch, computed } from "vue";
import Son from "../Son/index.vue";
const SonRef = ref(null);
let father = ref();
let sonNumInFather = ref(null);
// console.log("SonRef.value", SonRef.value);
onMounted(() => {
father.value = SonRef.value.sonNum;
console.log("SonRef.value", SonRef.value.sonNum);
console.log("SonRef.value", SonRef.value.changeSon);
// sonNumInFather.value = SonRef.value.sonNum;这样写也可以,但是不会是响应式数据,就永远是初始化的1,不会因为点击按钮就++
// 用watch可以实现sonNumInFather是响应数据
// watch(
// () => SonRef.value.sonNum,
// () => {
// father.value = SonRef.value.sonNum;
// console.log("hhhhh");
// }
// );
// 用computed可以实现sonNumInFather是响应数据
sonNumInFather.value = computed(() => {
return SonRef.value.sonNum;
});
});
const FatherChangeSon = () => {
SonRef.value.changeSon();
};
</script>
<template>
<button @click="FatherChangeSon">son+1</button>
<Son ref="SonRef"></Son>
{{ sonNumInFather }}
<!-- 下面这两个都渲染不成功,都不行 -->
<!-- {{ SonRef.sonNum }} -->
<!-- {{ father }} -->
// 很奇怪这样就可以了,可以正常显示,也不报错
{{ SonRef?.sonNum }}
</template>
<style scoped lang="scss"></style>