[英]How to dynamically import Vue 3 component?
According this article I would like to import component to view dynamically to my Vue 3 app.根据这篇文章,我想导入组件以动态查看我的 Vue 3 应用程序。 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你需要在Vue 3中使用
defineAsyncComponent
来延迟加载组件
import { defineAsyncComponent } from 'vue'
...
components: {
LatestBox: defineAsyncComponent(() => import('@/components/LatestBox.vue'))
}
https://v3.vuejs.org/guide/migration/async-components.html#overview 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
对于此类问题,vue 中有一个抽象组件
<componen :is="/* some-component */"/>
is
is a component, it can be a string (if you have imported the component), or a VueComponent object. is
是一个组件,它可以是一个字符串(如果你已经导入了组件),或者一个 VueComponent 对象。 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在这里您可以更改 componentManager 它将自动加载所需的组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.