Vue3 extends Property
In Vue 3,extends The property is a very useful feature that allows you to inherit from and extend existing components.
By using extends, you can reuse and customize existing component logic without rewriting code. This is very helpful for reducing code duplication and improving maintainability.
Use Cases
extends property is typically used in the following scenarios:
- Reuse Component Logic: When you have a base component whose logic other components need to inherit.
- Customize Component Behavior: When you need to customize or override certain behaviors on top of the inheritance.
- Build Configurable Components: Build more flexible, configurable components through inheritance and extension.
Basic Syntax
Example
import
BaseComponent from
'./BaseComponent.vue'
;
export
default
{
extends
:
BaseComponent
,
// Add new options or override existing ones here
}
;
In the code above, we used the extends property to inherit from the BaseComponent component. After that, you can add new options to this component, or override BaseComponent the existing options in it.
Example
1. Base Component
First, we define a base component BaseComponent.vue:
Example
{{ message }}
2. Inheriting Component
Next, we create a new component ExtendedComponent.vue, which inherits from BaseComponent, and overrides the message data:
Example
{{ message }}
In this example,ExtendedComponent inherits all the logic of BaseComponent , but overrides the message data. Therefore, the final rendered result is Hello from ExtendedComponent!.
Notes
-
Option Merging: When using the
extendsproperty, Vue performs option merging. Fordata,methodsand other object-type options, Vue performs a shallow merge. If properties share the same name, the child component's property overrides the parent component's property. -
Lifecycle Hooks: If both the child and parent components define the same lifecycle hook, both hook functions will be called, with the parent component's hook executing before the child's.
-
Template Override:
extendsThe property only inherits the logic part; the template part is not inherited. If you need to inherit the template, consider usingslotsormixins.
Vue3 Options API