Vue3 expose() Function
In Vue3,expose()the function is a tool used to expose a component's internal methods and properties in the Composition API.
expose()Usually used together with thesetup()function, it allows developers to explicitly specify which internal properties and methods of a component can be accessed externally.
Why do we need the expose() function?
In Vue2, a component's properties and methods are public by default and can be accessed directly from the outside. However, this design can lead to some problems, such as:
- Security issues: Internal methods may be accidentally exposed, leading to unsafe operations.
- Maintenance issues: It is difficult to track which properties and methods are used externally, increasing the complexity of maintenance.
Vue3 introduces theexpose()function, allowing developers to more precisely control the public interface of components, thereby solving the above problems.
How to use the expose() function?
Basic Syntax
Example
setup(props, context) {
const internalMethod = () => {
console.log('This is an internal method');
};
const publicMethod = () => {
console.log('This is a public method');
};
// Expose the publicMethod method
context.expose({
publicMethod
});
return {
internalMethod
};
}
};
Explanation
In the code above, we defined two methods:internalMethodandpublicMethod. Throughcontext.expose(), we only exposedpublicMethod, whileinternalMethodwill not be accessible externally.
Example Scenarios
1. Parent-Child Component Communication
Suppose we have a parent component and a child component, and the parent component needs to call a method of the child component.
Child component
Example
setup(props, context) {
const childMethod = () => {
console.log('Child method called');
};
context.expose({
childMethod
});
return {};
}
};
Parent component
Example
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
const childRef = ref(null);
onMounted(() => {
if (childRef.value) {
childRef.value.childMethod();
}
});
return {
childRef
};
}
};
2. Encapsulating a Component Library
When developing a component library, we may want to expose only some methods and properties to maintain the encapsulation and security of the components.
Example
setup(props, context) {
const internalState = ref('internal state');
const publicState = ref('public state');
const publicMethod = () => {
console.log('Public method called');
};
context.expose({
publicState,
publicMethod
});
return {
internalState
};
}
};
Notes
- Calling expose() multiple times: If called multiple times
expose(), only the content of the last call will be exposed. - Using in conjunction with ref: In the parent component, you can use
refto reference the child component and call its exposed methods. - Compatibility:
expose()is a new feature of Vue3. Make sure your project uses Vue3 or above.
Other Extensions
Vue3 Options API