关于vue3使用setup语法糖获取不到组件实例内部的变量

发布时间 2023-07-20 14:26:28作者: 独眼霹雳
// 子组件
<template>
  <div>{{count}}</div>
<template

<script setup>
  import { ref } from 'vue'

  const count = ref(0)
</script>
// 父组件
<template>
  <div>
    <Child ref="child" />
  </div>
<template

<script setup>
import { ref } from 'vue'
import Child from './child'

const child = ref()

onMounted(() => {
  // 此时打印为undefined
  console.log(child.value.count)
})
</script>

问题:如上述代码打印父组件通过获取组件实例child.value.count为undefined
原因: vue3使用 <script setup> 的组件是默认关闭的——即通过模板引用或者 $parent 链获取到的组件的公开实例,不会暴露任何在 <script setup> 中声明的绑定。

解决办法: 可以通过 defineExpose 编译器宏来显式指定在 <script setup> 组件中要暴露出去的属性:如图

// 子组件
<template>
  <div>{{count}}</div>
<template

<script setup>
  import { ref } from 'vue'

  const count = ref(0)
defineExpose({ count })
</script>

附官方文档: https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose