https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
使用 <script setup>
的组件是默认关闭的——即通过模板引用或者 $parent 链获取到的组件的公开实例,不会暴露任何在 <script setup>
中声明的绑定。
可以通过 defineExpose 编译器宏来显式指定在 <script setup>
组件中要暴露出去的属性:
<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)
defineExpose({
a,
b
})
</script>
当父组件通过模板引用的方式获取到当前组件的实例,获取到的实例会像这样 { a: number, b: number } (ref 会和在普通实例中一样被自动解包)。
示例:
父组件App.vue:
<script setup>
import Son from './components/son.vue'
import { onMounted, ref } from 'vue'
// 声明一个 ref 来存放该元素的引用
// 必须和模板里的 ref 属性的值同名
const h1Ref = ref(null)
const comRef = ref(null)
// 组件挂载完毕之后才能获取
// onMounted函数在组件挂载完成后执行
onMounted(() => {
console.log(h1Ref.value)
console.log(comRef.value)
})
</script>
<template>
<!-- 通过ref属性绑定ref对象 -->
<!-- 此处h1标签绑定了h1Ref这个对象 -->
<h1 ref="h1Ref">hello Vue3!</h1>
<Son ref="comRef"></Son>
</template>
<style scoped></style>
子组件son.vue:
<script setup>
import { ref } from 'vue'
const name = ref('test name')
const setName = () => {
name.value = 'new test name'
}
// 通过 defineExpose 编译器宏来显式指定在 <script setup> 组件中要暴露出去的属性
defineExpose({
name,
setName
})
</script>
<template>
<div>这是子组件</div>
</template>
<style scoped></style>
在浏览器中查看效果。从开发者工具控制台的打印信息,可以看到,在父组件中,访问到了在组件中通过defineExpose暴露的属性: