Vue.js - 从 ajax 调用加载组件 [英] Vue.js - load component from ajax call
问题描述
我正在尝试从 api 数据呈现或加载组件.为了解释更多,假设我已经将测试组件直接注入到我的父组件中,它可以工作.但是,当我尝试将组件标记保存在数据库中并运行 ajax 调用时,我的组件标记显示但不起作用,或者更确切地说是加载/渲染.请帮忙.
从我的 api 返回:
<代码>{"_id": "59411b05015ec22b5bcf814b","createdAt": "2017-06-14T11:16:21.662Z","updatedAt": "2017-06-14T12:41:28.069Z","name": "家","content": "<test-comp></test-comp>","slug": "/","navName": "家","__v": 0,着陆":真的,已发布":假}
我的父组件:
<div><test-comp></test-comp>//这有效<div v-html="page.content"></div>//但这不是 :(
模板><脚本>import { Api as defApi } from 'shared';从'./testComp'导入测试;导出默认{数据:() =>({页: {}}),创建(){defApi.get('api/pages/landing').then((res) => {this.page = res.data.body;});},成分: {testComp:测试}};
您只能在 v-html
标签中指定纯 HTML.因此,在传递给 v-html
的字符串中添加组件标记将不起作用.
如果您只是想指定组件类型,则可以使用 dynamic组件.在您的情况下,它可能如下所示:
<div><component :is="dynamicComponent"></component>
模板><脚本>import { Api as defApi } from 'shared';从'./testComp'导入测试;导出默认{数据:() =>({动态组件:空,}),创建(){defApi.get('api/pages/landing').then((res) => {this.dynamicComponent = res.data.componentType;//例如测试组合"});},成分: {testComp:测试}};
I'm trying to render or load components from api data. To explain more, let's say I've test-component, which I inject it directly in my parent component, works. But when I'm trying to save the component tag in database and run a ajax call, my component tag shows but doesn't work or rather load / render. Please help.
Return from my 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
}
My parent component:
<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>
You can only specify plain HTML in the v-html
tag. So, adding a component tag within the string passed to v-html
won't work.
If you are simply trying to specify the component type, you can use a dynamic component. In your case, it might look something like this:
<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>
这篇关于Vue.js - 从 ajax 调用加载组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!