Vue3 extends Property
In Vue3,extendsthe property is a very useful feature that allows you to inherit and extend existing components.
By usingextends, you can reuse and customize existing component logic without rewriting code. This is very helpful for reducing code redundancy and improving code maintainability.
Use Cases
extendsThe property is typically used in the following scenarios:
- Reuse component logic: When you have a base component and other components need to inherit its logic.
- Customize component behavior: When you need to customize or override certain behaviors based on inheritance.
- Build configurable components: By inheriting and extending, build more flexible and configurable components.
Basic Syntax
Example
export default {
extends: BaseComponent,
// Here you can add new options or override existing options
};
In the code above, we use theextendsproperty to inherit theBaseComponentcomponent. After that, you can add new options to this component, or overrideBaseComponentthe existing options in it.
Example
1. Base Component
First, we define a base componentBaseComponent.vue:
Example
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello from BaseComponent!'
};
}
};
</script>
2. Inheriting Component
Next, we create a new componentExtendedComponent.vue, which inherits fromBaseComponent, and overrides themessagedata:
Example
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
import BaseComponent from './BaseComponent.vue';
export default {
extends: BaseComponent,
data() {
return {
message: 'Hello from ExtendedComponent!'
};
}
};
</script>
In this example,ExtendedComponentinheritsBaseComponentall the logic of , but overrides themessagedata. Therefore, the final rendered result isHello 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 a property with the same name exists, the child component's property overrides the parent component's property.Lifecycle hooks: If both the child component and the parent component define the same lifecycle hook, both hook functions will be called, and the parent component's hook function will execute before the child component's hook function.
Template override:
extendsThe property only inherits the logic part; the template part will not be inherited. If you need to inherit the template, you can consider usingslotsormixins。
Other Extensions
Vue3 Options API