Preface
In Vue 3's Composition API,defineExpose
is an important helper function, specifically used in<script setup>
In mode, expose the properties and methods inside the component to use for the parent component. This article will analyze in detaildefineExpose
The functions, usage scenarios and precautions of , and combined with actual code examples to help you better understand and apply.
1. What is defineExpose?
defineExpose
It is one provided by Vue 3 that can only be found in<script setup>
The functions used in are used to explicitly expose properties or methods inside the component so that the parent component can passref
Access the exposed content of the child component.
effect
- In Vue 3,
<script setup>
The default is closed. The contents of the child component are not automatically exposed to the parent component. - use
defineExpose
Internal content can be optionally exposed, thereby avoiding unnecessary attribute leakage while providing better encapsulation.
2. Basic usage
grammar
defineExpose(exposedObject)
-
parameter:
exposedObject
, an object that defines the attribute or method to be exposed. - Return value:none.
Example: Exposing methods and data
<script setup> import { ref } from 'vue'; // The state and methods inside the subcomponentconst count = ref(0); function increment() { ++; } //Expose to parent component via defineExposedefineExpose({ count, increment }); </script> <template> <div> <p>Counter subcomponent:{{ count }}</p> </div> </template>
In the parent component:
<script setup> import { ref } from 'vue'; import Counter from './'; // Get subcomponent instance through refconst counterRef = ref(null); function callChildMethod() { (); // Methods to call subcomponents ('Subcomponent count value:', ); // Access the exposed properties of the child component} </script> <template> <Counter ref="counterRef" /> <button @click="callChildMethod">Calling child component method</button> </template>
Running results
- Click the button, and the parent component calls the child component’s
increment
Method, subcomponentcount
Value increases. - Parent component through child component
ref
Visitedcount
andincrement
。
3. Why do you need defineExpose?
Default behavior: enclosed <script setup>
In Vue 3<script setup>
In , the status and methods of the component are by defaultPrivate. This means that the parent component even passesref
Referring to a child component instance, no content can be accessed.
For example:
<script setup> const msg = 'Hello Vue'; </script>
In the parent component, even ifref
Accessing child components, it cannot be accessedmsg
。
Explicit exposure: Improve security
passdefineExpose
, Developers can explicitly select what to expose, thereby avoiding parent components from accessing unnecessary internal state or methods, and providing better component encapsulation.
4. Typical usage scenarios of defineExpose
4.1 Exposure method
When the parent component needs to call the child component's method, you can usedefineExpose
。
<script setup> function greet() { ('The child component method is called! '); } defineExpose({ greet }); </script>
In the parent component:
<template> <ChildComponent ref="child" /> <button @click="()">Calling child component method</button> </template> <script setup> import { ref } from 'vue'; import ChildComponent from './'; const child = ref(null); </script>
4.2 Cooperate with dynamic templates or status management
When a child component needs to expose a dynamic state for use by the parent component:
<script setup> import { ref } from 'vue'; const isLoading = ref(false); function startLoading() { = true; } function stopLoading() { = false; } defineExpose({ isLoading, startLoading, stopLoading }); </script>
Parent component:
<script setup> import ChildComponent from './'; import { ref } from 'vue'; const childRef = ref(null); function toggleLoading() { (); setTimeout(() => { (); }, 2000); } </script> <template> <ChildComponent ref="childRef" /> <button @click="toggleLoading">load 2 Second</button> </template>
4.3 Complex scenarios: Dynamic parent-child component interaction
Sometimes the parent component needs to dynamically render content based on the status of the child component, such as form verification, step management, etc.
Example: Subcomponent exposure verification method
<script setup> import { ref } from 'vue'; const formData = ref({ name: '', age: null }); function validate() { const isValid = !== '' && > 0; return isValid; } defineExpose({ formData, validate }); </script> <template> <div> <input v-model="" placeholder="Enter a name" /> <input v-model="" type="number" placeholder="Input Age" /> </div> </template>
Parent component calls verification:
<script setup> import { ref } from 'vue'; import FormComponent from './'; const formRef = ref(null); function submitForm() { if (()) { ('Form verification passed! '); } else { ('Form verification failed! '); } } </script> <template> <FormComponent ref="formRef" /> <button @click="submitForm">submit</button> </template>
5. Things to note
Only used in <script setup>:
defineExpose
It is specially designed for<script setup>
Designed, not used for ordinary<script>
orsetup()
in the function.Clearly exposed content:
It is not recommended to directly expose the internal state of the entire component. Only the necessary parts should be exposed to maintain the encapsulation of the component.ref must be correctly bound:
The parent component is only set for the child component.ref
Only after attributes can you passref
Access the exposed content of the child component.Avoid abuse:
If the parent component frequently depends on the internal state of the child component, it may indicate that the parent component and the child component are not divided clearly.
6. Summary
defineExpose
is a powerful helper function in Vue 3 for closed<script setup>
Explicitly expose part of the component in mode。 It enhances the interaction between components while maintaining the encapsulation of components. By reasonable usedefineExpose
, can improve code flexibility and maintainability.