Vue3
中setup
通过ref
获取子组件的属性
主要依赖defineExpose
子组件通过 defineExpose
将数据抛出
<template>
<div class="test-com">testCom</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const testText = ref('我是子组件的数据')
defineExpose({
text: testText
})
</script>
父组件通过给子组件绑定ref
然后结合nextTick
回调函数获取子组件的数据
<template>
<div>
<TestCom ref="getTestComRef" />
{{ showText }}
</div>
</template>
<script lang="ts" setup>
import { nextTick, ref } from 'vue'
import TestCom from './components/TestCom.vue'
const getTestComRef = ref<{
text: string
}>()
const showText = ref()
nextTick(() => {
showText.value = getTestComRef.value?.text
})
</script>
效果图