使用 <script setup>写法会导致父组件无法访问到子组件中的属性和方法,需要使用defineExpose将其暴露出去。
子组件(children.vue):
<template>
<div>
{{ str }}
</div>
</template>
<script setup lang="ts">
import { ref, defineExpose } from 'vue';
const str = ref('嘻嘻');
defineExpose({ str }); // 敲黑板 看重点
</script>
父组件(parent.vue):
<template>
<div>
<children ref="childrenRef" />
</div>
</template>
<script setup lang="ts">
import children from './children.vue';
import { ref } from 'vue';
const childrenRef = ref(null);
console.log(childrenRef.value?.str);
</script>