How do you register a local component?
Method 1: via <script setup> (modern and most convenient)
In <script setup> mode, importing a component automatically registers it, no additional configuration is needed.
Example:
javascript
<!-- Parent.vue -->
<script setup>
import UserCard from './UserCard.vue'
</script>
<template>
<UserCard />
</template>Done, the component is registered locally.
This is the most popular approach in modern Vue 3 projects.
Method 2: via a regular <script> (Options API or Composition API without setup)
If you are not using <script setup>, you need to explicitly list the component in the components option.
Example (Composition API without setup):
javascript
<script>
import UserCard from './UserCard.vue'
export default {
components: {
UserCard,
},
}
</script>
<template>
<UserCard />
</template>Example (Options API):
javascript
<script>
import ProductItem from './ProductItem.vue'
export default {
name: "ProductList",
components: {
ProductItem,
},
}
</script>
<template>
<ProductItem />
</template>Which approach to choose?
Use <script setup> if:
- the project is on Vue 3
- you want to write less code
- you want more readable components
Use components: {} only if:
- the project inherits the old Vue 2 style
- you need compatibility with Options API code
Summary (in short)
Local component registration in Vue 3:
In <script setup>:
javascript
<script setup>
import MyComponent from './MyComponent.vue'
</script>In a regular <script>:
javascript
components: {
MyComponent
}Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.