我正在构建一个使用vue和nuxt的网站,通过rest从一个服务站点加载数据。
我想让客户端能够使用自定义字段修改页面模板,因此我需要动态地创建vue模板,这些组件是根据放置在wordpress页面编辑器中的自定义字段生成的。
这是简化的,但例如,如果客户端生成一个带有三个自定义字段的页面:
[custom-field type='hero']
[custom-field type='slider']
[custom-field type='testimonial']
我可以通过json对象中的rest获取字段信息,如下所示:
page: {
acf: [
{field 1: {
{type: 'hero'},
{content: '...'}
},
{field 2: {
{type:'slider'},
{content: '...'}
},
{field 3: {
{type:'testimonial'},
{content: '...'}
}
}
}
我将把它引入到我的vue应用程序中,然后我将从映射到自定义字段类型的可能组件列表中动态生成模板。上述产出如下:
<template>
<Hero ... />
<Slider ... />
<Testimonial ... />
</template>
这是否使用v-is指令(https://v2.vuejs.org/v2/guide/components-dynamic-async.html)来完成,比如:
<component v-for="field in custom-fields" v-is="field.type" :data="field.data"/>?
这个是可能的吗?任何帮助都将不胜感激。
发布于 2020-05-25 02:43:14
您可以在Nuxt中动态注册和显示组件,但有一些注意事项。
方法1- SSR & SSG支持
此方法将动态注册组件并维护服务器端呈现/静态站点生成的完整性。
这里唯一的折衷之处是,您需要列出的名称和文件位置,所有可能导入的组件。对于用例来说,这不应该太麻烦(我不认为您有太多的ACF字段),但是如果您打算从它构建一个完整的组件库,这可能是一项很长的工作。
<template>
<div>
<div v-for="field in page.acf" :key="field.uniqueId">
<component :is="field.type" :my-prop="field.content" />
</div>
</div>
</template>
<script>
export default {
components: {
hero: () => import('~/components/hero.vue'),
slider: () => import('~/components/slider.vue'),
testimonial: () => import('~/components/testimonial.vue')
},
data() {
return {
page: {
acf: [
{
uniqueId: 1,
type: 'hero',
content: '...'
},
{
uniqueId: 2,
type: 'slider',
content: '...'
},
{
uniqueId: 3,
type: 'testimonial',
content: '...'
}
]
}
}
}
}
</script>
方法2-客户端只呈现
此方法允许您以编程方式注册组件的名称和文件位置。这使您不必逐个写出每个组件,但代价是不支持SSR或SSG。然而,这可能是更好的,如果你要走SPA路线。
<template>
<div>
<div v-for="field in page.acf" :key="field.uniqueId">
<no-ssr>
<component :is="field.type" :my-prop="field.content" />
</no-ssr>
</div>
</div>
</template>
<script>
import Vue from 'vue'
export default {
data() {
return {
page: {
acf: [
{
uniqueId: 1,
type: 'hero',
content: '...'
},
{
uniqueId: 2,
type: 'slider',
content: '...'
},
{
uniqueId: 3,
type: 'testimonial',
content: '...'
}
]
}
}
},
mounted() {
const sections = this.page.acf
for (let i = 0; i < sections.length; i++) {
Vue.component(sections[i].type, () =>
import(`~/components/${sections[i].type}.vue`)
)
}
}
}
</script>
请注意,<no-ssr>
标记已被废弃,如果您使用的是v2.9.0
之上的Nuxt,则应该使用<client-only>
。
关于你的问题的注记
希望这能有所帮助!
如果有人知道一种方法,允许您在维护SSG的同时以编程方式设置组件名称和组件文件位置--请告诉我!
https://stackoverflow.com/questions/61356066
复制相似问题