SoFunction
Updated on 2025-04-05

In-depth analysis of the usage of defineExpose function in Vue3

Preface

In Vue 3's Composition API,defineExposeis 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 detaildefineExposeThe functions, usage scenarios and precautions of  , and combined with actual code examples to help you better understand and apply.

1. What is defineExpose?

defineExposeIt 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 passrefAccess 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.
  • usedefineExposeInternal content can be optionally exposed, thereby avoiding unnecessary attribute leakage while providing better encapsulation.

2. Basic usage

grammar

defineExpose(exposedObject)
  • parameterexposedObject, an object that defines the attribute or method to be exposed.
  • Return value:none.

Example: Exposing methods and data

&lt;script setup&gt;
import { ref } from 'vue';

// The state and methods inside the subcomponentconst count = ref(0);

function increment() {
  ++;
}

//Expose to parent component via defineExposedefineExpose({
  count,
  increment
});
&lt;/script&gt;

&lt;template&gt;
  &lt;div&gt;
    &lt;p&gt;Counter subcomponent:{{ count }}&lt;/p&gt;
  &lt;/div&gt;
&lt;/template&gt;

In the parent component:

&lt;script setup&gt;
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}
&lt;/script&gt;

&lt;template&gt;
  &lt;Counter ref="counterRef" /&gt;
  &lt;button @click="callChildMethod"&gt;Calling child component method&lt;/button&gt;
&lt;/template&gt;

Running results

  • Click the button, and the parent component calls the child component’sincrementMethod, subcomponentcountValue increases.
  • Parent component through child componentrefVisitedcountandincrement

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 passesrefReferring to a child component instance, no content can be accessed.

For example:

<script setup>
const msg = 'Hello Vue';
</script>

In the parent component, even ifrefAccessing 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

&lt;script setup&gt;
function greet() {
  ('The child component method is called!  ');
}
defineExpose({ greet });
&lt;/script&gt;

In the parent component:

&lt;template&gt;
  &lt;ChildComponent ref="child" /&gt;
  &lt;button @click="()"&gt;Calling child component method&lt;/button&gt;
&lt;/template&gt;

&lt;script setup&gt;
import { ref } from 'vue';
import ChildComponent from './';

const child = ref(null);
&lt;/script&gt;

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:

&lt;script setup&gt;
import ChildComponent from './';
import { ref } from 'vue';

const childRef = ref(null);

function toggleLoading() {
  ();
  setTimeout(() =&gt; {
    ();
  }, 2000);
}
&lt;/script&gt;

&lt;template&gt;
  &lt;ChildComponent ref="childRef" /&gt;
  &lt;button @click="toggleLoading"&gt;load 2 Second&lt;/button&gt;
&lt;/template&gt;

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

&lt;script setup&gt;
import { ref } from 'vue';

const formData = ref({ name: '', age: null });

function validate() {
  const isValid =  !== '' &amp;&amp;  &gt; 0;
  return isValid;
}

defineExpose({ formData, validate });
&lt;/script&gt;

&lt;template&gt;
  &lt;div&gt;
    &lt;input v-model="" placeholder="Enter a name" /&gt;
    &lt;input v-model="" type="number" placeholder="Input Age" /&gt;
  &lt;/div&gt;
&lt;/template&gt;

Parent component calls verification:

&lt;script setup&gt;
import { ref } from 'vue';
import FormComponent from './';

const formRef = ref(null);

function submitForm() {
  if (()) {
    ('Form verification passed!  ');
  } else {
    ('Form verification failed!  ');
  }
}
&lt;/script&gt;

&lt;template&gt;
  &lt;FormComponent ref="formRef" /&gt;
  &lt;button @click="submitForm"&gt;submit&lt;/button&gt;
&lt;/template&gt;

5. Things to note

  • Only used in <script setup>:
    defineExposeIt 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.refOnly after attributes can you passrefAccess 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

defineExposeis 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.