Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue3 extends Property

Vue3 extends Property


Vue3 Options API Vue3 Options API

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:

  1. Reuse Component Logic: When you have a base component whose logic other components need to inherit.
  2. Customize Component Behavior: When you need to customize or override certain behaviors on top of the inheritance.
  3. 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

2. Inheriting Component

Next, we create a new component ExtendedComponent.vue, which inherits from BaseComponent, and overrides the message data:

Example

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

  1. Option Merging: When using the extends property, Vue performs option merging. For data, methods and 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.

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

  3. Template Override:extends The property only inherits the logic part; the template part is not inherited. If you need to inherit the template, consider using slots or mixins.


Vue3 Options API Vue3 Options API