英文:
Dynamic component via Nuxt3 / Vue3
问题
I want to create a few components dynamically, but at the moment It doesn't work.
Here is a simple example. I cannot assign a var to the :is
attribute
<template>
<div class="the-modules">
<component :is="name" />
</div>
</template>
<script setup>
import ModuleStage from './ModuleStage.vue';
const name = "ModuleStage"
</script>
英文:
I want to create a few components dynamically, but at the moment It doesn't work.
Here is a simple example. I cannot assign a var to the :is
attribute
<template>
<div class="the-modules">
<component :is="name" />
</div>
</template>
<script setup>
import ModuleStage from './ModuleStage.vue';
const name = "ModuleStage"
</script>
答案1
得分: 2
以下是翻译好的部分:
只需将您的动态组件(仅限这些组件)放在components/global/
目录下。
您还可以在您的Nuxt配置中指定一个单独的目录:
export default defineNuxtConfig({
components: {
dirs: [
{
"path": "~/components/my-dynamic-components",
"global": true
},
"~/components"
]
},
})
然后,您可以直接使用它们,无需解析或手动导入任何内容:
<component :is="'MyAwesomeComponent'" />
在文档中了解更多信息:
- https://nuxt.com/docs/api/configuration/nuxt-config#components
- https://nuxt.com/docs/guide/directory-structure/components#dynamic-components
英文:
As it is not always possible to predict components and import them manually or work with resolveComponent
(i.e. you work with a CMS), i would recommend to work with global components in nuxt3.
Just place your dynamic components (and only these) under components/global/
You can also specify a seperate directory in your nuxt config:
export default defineNuxtConfig({
components: {
dirs: [
{
"path": "~/components/my-dynamic-components",
"global": true
},
"~/components"
]
},
})
Then you can just use them without resolving or import anything:
<component :is="'MyAwesomeComponent'" />
Read more in the Documentation:
答案2
得分: 1
<script setup>
不能特别用于动态组件的字符串:文档
您可以使用导入的引用本身:
<template>
<div class="the-modules">
<component :is="ModuleStage" />
</div>
</template>
<script setup>
import ModuleStage from './ModuleStage.vue';
</script>
或者,您可以使用选项 API,其中可以使用字符串:
<template>
<div class="the-modules">
<component :is="name" />
</div>
</template>
<script>
import ModuleStage from './ModuleStage.vue';
export default {
components: { ModuleStage },
data() {
return {
name: 'ModuleStage'
};
}
};
</script>
英文:
<script setup>
specifically can not use strings for dynamic components: Documentation
You can use the imported reference itself
<template>
<div class="the-modules">
<component :is="ModuleStage" />
</div>
</template>
<script setup>
import ModuleStage from './ModuleStage.vue';
</script>
or you can use Options API where strings can be used
<template>
<div class="the-modules">
<component :is="name" />
</div>
</template>
<script>
import ModuleStage from './ModuleStage.vue';
export default {
components: { ModuleStage },
data() {
return {
name: 'ModuleStage'
};
}
};
</script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论