Can be passeddefineExpose
Compiler macros are explicitly specified in<script setup>
Attributes to be exposed in the component:
<script setup> import { ref } from 'vue' const a = 1 const b = ref(2) defineExpose({ a, b }) </script>
When the parent component obtains the current component instance through template reference, the obtained instance will look like this{ a: number, b: number }
(ref will be automatically unpacked just like in normal instances)
example
Parent component
<template> <h2>defineExpose use Parent component</h2> <child ref="getChildData"></child> </template> <script setup lang="ts"> import Child from "@/components/" import { ref,onMounted,toRaw} from 'vue' // The documentation says that the component is closed when the setup is written on script // That is to say, the parent component cannot access the data of the child component // At this time, we need to use defineExpose to expose the data to be passed so that external access can be // Similarly, you can also receive external values const getChildData = ref(null) const obj = { name: 'alan', desc: 'Big idiot', age: 18 } const cc= ?.['num'] (cc) //undefined, the data exposed by the child component has not been found at this time onMounted(()=>{ //Get the data data of the child component, and when to obtain it according to your business const bb:any= ?.['updata'] (bb()) // 123, At this time, the initial value of the child component is obtained, because data has not been passed to the child component yet const a:any= ?.['getData'] a(obj) ///// Pass data to subcomponents const b:any= ?.['updata'] const c= ?.['num'] (toRaw(b())) // {name: 'alan', desc: 'big fool', age: 18} , what I get here is a proxy, so I need to convert the toRaw() method into an object (c) // 666 }) </script> <style scoped> </style>
Subcomponents
<template> <h2>defineExpose use Subcomponents</h2> <div>{{ data }}</div> </template> <script setup lang="ts"> import { ref, defineExpose } from 'vue' const data = ref(123) const num = ref(666) defineExpose({ updata(){ return //Expose the data that the parent component can get. The value is 123 }, getData(res:any){ = res //The value passed by the parent component is assigned to data // At this time, data becomes Proxy // { // name: 'alan', // desc: 'Big Boy', // age: 18 // } }, num }) </script> <style scoped> </style>
This is the end of this article about vue3 using defineExpose. For more related content about vue3 using defineExpose, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!