Home  >  Article  >  Web Front-end  >  How to use defineExpose in vue3

How to use defineExpose in vue3

王林
王林forward
2023-05-17 10:04:051822browse

You can use the defineExpose compiler macro to explicitly specify the properties to be exposed in the 5101c0cdbdc49998c642c71f6b6410a8 component:

<script setup>
import { ref } from &#39;vue&#39;

const a = 1
const b = ref(2)

defineExpose({
  a,
  b
})
</script>

When the parent component passes The instance of the current component is obtained through template reference. The obtained instance will be like this { a: number, b: number } (ref will be automatically unpacked like in a normal instance)

Example

Parent component

<template>
  <h3>defineExpose 使用 父组件</h3>
  <child ref="getChildData"></child>

</template>

<script setup lang="ts">
import Child from "@/components/exposeChildren.vue"
import { ref,onMounted,toRaw} from &#39;vue&#39;
    // 文档说setup写在script上组件是关闭的
    // 也就是说父组件使用getChildData.xxx访问不到子组件的数据
    // 此时我们需要用defineExpose把需要传递的数据暴露出去,这样外部才能访问到
    // 同理也可以接收外部传来的值

const getChildData = ref(null)
const obj = {
    name: &#39;alan&#39;,
    desc: &#39;大笨蛋&#39;,
    age: 18
}

const cc= getChildData.value?.[&#39;num&#39;]
console.log(cc) //undefined,此时还未找到子组件暴露的数据

onMounted(()=>{
  //获取子组件的data数据,什么时候获取根据自己业务来
  const bb:any= getChildData.value?.[&#39;updata&#39;]
  console.log(bb()) // 123,这时候得到的是子组件的初始值,因为还未给子组件传递数据
  const a:any= getChildData.value?.[&#39;getData&#39;] 
  a(obj) ////给子组件传递数据
  const b:any= getChildData.value?.[&#39;updata&#39;]
  const c= getChildData.value?.[&#39;num&#39;]
  console.log(toRaw(b())) // {name: &#39;alan&#39;, desc: &#39;大笨蛋&#39;, age: 18} ,这里得到的是个proxy,所以需要toRaw()方法转成对象 
  console.log(c) // 666
})


</script>
<style scoped>
</style>

Child component

<template>
  <h3>defineExpose 使用 子组件</h3>
  <div>{{ data }}</div>
</template>

<script setup lang="ts">
import { ref, defineExpose } from &#39;vue&#39;

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: &#39;alan&#39;,
        //     desc: &#39;大笨蛋&#39;,
        //     age: 18
        //     }
    },
    num
})
</script>
<style scoped>
</style>

The above is the detailed content of How to use defineExpose in vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete