According this article I would like to import component to view dynamically to my Vue 3 app. The code of the view looks like:
<template>
<div class="page">
<latest-box v-if="showLatestBox" />
</div>
</template>
<script>
// @ is an alias to /src
// This works well.
//import LatestBox from '@/components/LatestBox.vue'
export default {
name: 'Page 1',
data() {
return {
showLatestBox: true,
}
},
components: {
LatestBox: () => import('@/components/LatestBox.vue') // This does not work
}
}
</script>
Code does not throw any errors but I dont see the component on the page. If I use first import style it works. Am I missing somethig?
You need to use defineAsyncComponent
in Vue 3 to lazy load components
import { defineAsyncComponent } from 'vue'
...
components: {
LatestBox: defineAsyncComponent(() => import('@/components/LatestBox.vue'))
}
https://v3.vuejs.org/guide/migration/async-components.html#overview
If you want to load them dynamically, i guess you may not know which component you need at the moment. For such issues there is an abstranct component in vue
<componen :is="/* some-component */"/>
is
is a component, it can be a string (if you have imported the component), or a VueComponent object. You can use watchers to autoimport components, for example:
data() {
return {
passedComponent: null,
componentManager: '',
}
},
watch: {
componentManager(newValue) {
this.passedComponent = import(`@/components/${newValue}.vue`)
}
}
And your template would look like that
<template>
<div class="page">
<component :is="passedComponent" />
</div>
</template>
Here you can change componentManager and it will load needed component automatically
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.