Smi*_*Ray 2 api vue.js vue-component axios vuejs2
我正在尝试从api数据呈现或加载组件。为了进一步说明,假设我有测试组件,可以直接将其注入到我的父组件中。但是,当我尝试将component标签保存在数据库中并运行ajax调用时,我的component标签会显示但不起作用,或者是加载/渲染。请帮忙。
从我的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
}
Run Code Online (Sandbox Code Playgroud)
我的父组件:
<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>
Run Code Online (Sandbox Code Playgroud)
您只能在v-html
标记中指定纯HTML 。因此,在传递给的字符串中添加一个组件标签v-html
将不起作用。
如果您只是尝试指定组件类型,则可以使用动态组件。在您的情况下,可能看起来像这样:
<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>
Run Code Online (Sandbox Code Playgroud)