[Vue3+Ts] The reason why the parent component cannot obtain the child component instance using setup syntax sugar

error code:

Subassembly:

<template>
    <div></div>
</template>

<script setup lang="ts">
// 引入defineExpose 将数据暴露
import {defineExpose} from 'vue'
// 定义一个变量
let test = {name: 'xiaoman'}
// 暴露给父组件
defineExpose({test})
</script>

The parent component receives:

<template>
  <Child ref="child" ></Child>
</template>

<script setup lang="ts">
import Child from './Child'
import { ref, onMounted } from 'vue'

const childComp = ref<InstanceType<typeof Child>>()

onMounted(() => {
  console.log(childComp.value) // undefined
  console.log(childComp.value.test, '???') // 报错:找不到test变量
})
</script>

<style scoped>

</style>

Unable to obtain subcomponent instances and exposed objects in onMounted

Later I found the problem:

The variable receiving the subcomponent instance must be consistent with the assignment of ref in the subcomponent tag! ! !

The variable receiving the subcomponent instance must be consistent with the assignment of ref in the subcomponent tag! ! !

The variable receiving the subcomponent instance must be consistent with the assignment of ref in the subcomponent tag! ! !

 Corrected parent component code:

<template>
  <Child ref="child" :title="name" :arr="[1,2,3]" @on-click="getName" ></Child>
</template>

<script setup lang="ts">
import Child from './Child'
import { ref, onMounted } from 'vue'

// child这个变量必须和子组件里面的ref定义的一模一样
const child = ref<InstanceType<typeof Child>>()

onMounted(() => {
  console.log(child.value)
  console.log(child.value.test, '???')
})
</script>

<style scoped>

</style>

The value can also be printed:

 

Let’s briefly summarize the reasons why the parent component cannot obtain the child component using ref under the Vue3 setup syntax sugar:

1. The data of the subcomponent is not exposed using defineExpose

2. The assignment of ref to the subcomponent tag is inconsistent with the naming of the parent component when assigning variables.

3. No use to obtain .value

4. It is not obtained in onMounted, and the component has not been mounted yet.

Guess you like

Origin blog.csdn.net/Weiqian_/article/details/132191401