可以通过 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 会和在普通实例中一样被自动解包)
父组件
<template>
<h3>defineExpose 使用 父组件</h3>
<child ref="getChildData"></child>
</template>
<script setup lang="ts">
import Child from "@/components/exposeChildren.vue"
import { ref,onMounted,toRaw} from 'vue'
// 文档说setup写在script上组件是关闭的
// 也就是说父组件使用getChildData.xxx访问不到子组件的数据
// 此时我们需要用defineExpose把需要传递的数据暴露出去,这样外部才能访问到
// 同理也可以接收外部传来的值
const getChildData = ref(null)
const obj = {
name: 'alan',
desc: '大笨蛋',
age: 18
}
const cc= getChildData.value?.['num']
console.log(cc) //undefined,此时还未找到子组件暴露的数据
onMounted(()=>{
//获取子组件的data数据,什么时候获取根据自己业务来
const bb:any= getChildData.value?.['updata']
console.log(bb()) // 123,这时候得到的是子组件的初始值,因为还未给子组件传递数据
const a:any= getChildData.value?.['getData']
a(obj) ////给子组件传递数据
const b:any= getChildData.value?.['updata']
const c= getChildData.value?.['num']
console.log(toRaw(b())) // {name: 'alan', desc: '大笨蛋', age: 18} ,这里得到的是个proxy,所以需要toRaw()方法转成对象
console.log(c) // 666
})
</script>
<style scoped>
</style>子组件
<template>
<h3>defineExpose 使用 子组件</h3>
<div>{{ data }}</div>
</template>
<script setup lang="ts">
import { ref, defineExpose } from 'vue'
const data = ref(123)
const num = ref(666)
defineExpose({
updata(){
return data.value //暴露出去父组件可以拿到data的数据.此时值为123
},
getData(res:any){
data.value = res //父组件传递来的值赋值给data
// 此时的data变成了 Proxy
// {
// name: 'alan',
// desc: '大笨蛋',
// age: 18
// }
},
num
})
</script>
<style scoped>
</style>以上就是vue3怎么使用defineExpose的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号