我正在尝试从api数据中渲染或加载组件。为了解释更多,让我说我的测试组件,我将其直接注入我的父组件,工作。但是当我尝试在数据库中保存组件标记并运行ajax调用时,我的组件标记显示但不起作用或者更确切地说是加载/呈现。请帮忙。
从我的api回来:
{
"_id": "59411b05015ec22b5bcf814b",
"createdAt": "2017-06-14T11:16:21.662Z",
"updatedAt": "2017-06-14T12:41:28.069Z",
"name": "Home",
"content": "<test-comp></test-comp>",
"slug": "/",
"navName": "Home",
"__v": 0,
"landing": true,
"published": false
}
我的父组件:
<template>
<div>
<test-comp></test-comp> // This works
<div v-html="page.content"></div> // But this doesn't :(
</div>
</template>
<script>
import { Api as defApi } from 'shared';
import test from './testComp';
export default {
data: () => ({
page: {}
}),
created() {
defApi.get('api/pages/landing')
.then((res) => {
this.page = res.data.body;
});
},
components: {
testComp: test
}
};
</script>
答案 0 :(得分:5)
您只能在v-html
标记中指定纯HTML。因此,在传递给v-html
的字符串中添加组件标记将无法正常工作。
如果您只是尝试指定组件类型,则可以使用dynamic component。在您的情况下,它可能看起来像这样:
<template>
<div>
<component :is="dynamicComponent"></component>
</div>
</template>
<script>
import { Api as defApi } from 'shared';
import test from './testComp';
export default {
data: () => ({
dynamicComponent: null,
}),
created() {
defApi.get('api/pages/landing')
.then((res) => {
this.dynamicComponent = res.data.componentType; // e.g. "testComp"
});
},
components: {
testComp: test
}
};
</script>