首页 > 试题广场 >

在 Vue 3 的 `` 语法糖中...

[单选题]
在 Vue 3 的 `<script setup>` 语法糖中,组件的实例默认是关闭的,即父组件通过模板引用 (template ref) 无法访问其任何属性和方法。哪个宏函数可以用来显式地暴露组件的公共接口?
  • `defineProps`
  • `defineEmits`
  • `defineModel`
  • `defineExpose`
 <script setup> 中组件默认是封闭的,父组件通过 ref 拿到的实例什么都访问不到。defineExpose 用于显式声明要暴露给父组件的内容:
  <!-- Child.vue -->
  <script setup>
  import { ref } from 'vue'

  const count = ref(0)
  const reset = () => { count.value = 0 }

  // 只有这里列出的才能被父组件访问
  defineExpose({ count, reset })
  </script>

  <!-- Parent.vue -->
  <template>
    <Child ref="childRef" />
    <button @click="childRef.reset()">重置</button>
  </template>

  <script setup>
  import { ref } from 'vue'
  const childRef = ref(null)
  </script>


发表于 2026-04-15 17:11:41 回复(0)