UPDATE: there is an official guide now.
Vue 2 docs has a great way to automatically register base components.
Fortunately this keeps working in Vue 3 with minimal changes.
Get started
As soon as we start a project using vue-cli and Vue 3 we will see something like this in the main.js
file:
createApp(App).mount('#app')
Let's change it up a bit to add our base components:
const app = createApp(App)
app.mount('#app')
Before mount the app we will add our registration.
Here we require all components that are inside components
folder:
const requireComponent = require.context(
'./components',
true,
/Base[A-Z]\w+.(vue|js)$/
)
If you prefer to have folders
and index.vue
files for components you need to change the regex:
/Base[A-Z]\w+\/index.vue$/
Finally, you need to iterate over all components and register them using the Vue instance we assigned to app
variable:
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = upperFirst(
camelCase(
fileName
.split('/')
.pop()
.replace(/\.\w+$/, '')
)
)
app.component(
componentName,
componentConfig.default || componentConfig
)
})
Is this real life?
There is a demo app to show the real life implementation.
Top comments (0)