【发布时间】:2024-01-08 11:42:01
【问题描述】:
场景:
我在universal 模式下使用 Nuxt。该应用程序与一个无头 CMS 配合使用,该 CMS 提供了应呈现的组件的简单布局,以及组件名称及其道具 - 如下所示:
[
{
"tag": "div",
"class": "col",
"component": "dogs",
"props": {
"dogs": [
{
"id": 1,
"name": "Barky"
},
{
"id": 2,
"name": "Jumpy"
}
]
}
},
{
"tag": "div",
"class": "col",
"component": "cats",
"props": {
"cats": [
{
"id": 1,
"name": "Miouwy"
},
{
"id": 2,
"name": "Fluffy"
}
]
}
}
]
据我了解,我必须在 Nuxt 制作“快照”并将其交付给客户端之前将组件应用到 DOM。我的计划是在created() 生命周期中挂载组件——也就是说,只看名称,而不是要走的路。
主要问题:
我想将组件动态挂载到尚不存在的 DOM。
作为我想逃避的事情的一个例子 - 在 Nuxt 交付快照之后安装组件 - 在 mounted() 生命周期中。
<template>
<section class="container">
<div ref="layout-container" class="row"></div>
</section>
</template>
<script>
import { mapGetters } from 'vuex';
import Vue from 'vue';
import Dogs from '@/components/Dogs';
import Cats from '@/components/Cats';
export default {
components: {
Dogs,
Cats
},
fetch({ store }) {
store.dispatch('landing/updateContent');
},
computed: {
...mapGetters({
content: 'landing/content',
})
},
beforeCreate() {
Vue.component('dogs', Dogs);
Vue.component('cats', Cats);
},
mounted() {
this.content.forEach((item) => {
const CompClass = Vue.component(item.component);
const instance = new CompClass({ propsData: item.props }).$mount();
this.$refs['layout-container'].appendChild(instance.$el);
})
}
};
</script>
非常感谢您提前提供任何指示!
【问题讨论】:
标签: vue.js content-management-system vuex server-side-rendering nuxt.js