Vue3 components property


Vue3 选项式 APIVue3 Options API

In Vue3,componentsthe property is used to register local components. Viacomponentscomponents registered with the property can only be used in the current component and do not affect other components. This allows us to reuse the same component name in different components without naming conflicts.


How to use the Components property?

Usingcomponentsthe property is very simple. You just need to, in the Vue component'sscriptsection, define ancomponentsobject, and then add the component you want to register as a property of that object.

1. Example code

Example

<template>
  <div>
    <MyComponent />
  </div>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
  components: {
    MyComponent
  }
}
</script>

2. Code explanation

  • <MyComponent />: This is the tag of the local component we registered and use in the template.
  • import MyComponent from './MyComponent.vue';: We first need to import the component to be registered.
  • components: { MyComponent }: In thecomponentsobject, weMyComponentregister the component as a local component.

Why use the Components property?

Usingcomponentsthe property to register local components has the following benefits:

  1. Modularity: Break components into smaller parts, making code easier to maintain and understand.
  2. Reusability: You can reuse the same components in different components without redefining them.
  3. Namespace: The registration scope of local components is limited to the current component, avoiding global naming conflicts.

Notes

  • Scope of local components: Components registered throughcomponentsthe property can only be used in the current component. If you need to use the same component in other components, you need to register it again in those components.
  • Component naming: Component names usually use PascalCase, but when used in templates, kebab-case can be used. For example,MyComponentcan be written in the template as<my-component />。

Vue3 选项式 APIVue3 Options API

Other extensions