Vue.js-从ajax调用加载组件 [英] Vue.js - load component from ajax call

查看:333
本文介绍了Vue.js-从ajax调用加载组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从api数据呈现或加载组件.为了进一步说明,假设我有一个测试组件,可以直接将其注入到我的父组件中.但是,当我尝试将component标签保存在数据库中并运行ajax调用时,我的component标签会显示但不起作用,或者是加载/渲染.请帮忙.

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.

从我的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>

推荐答案

您只能在v-html标记中指定纯HTML.因此,在传递给v-html的字符串中添加组件标签将不起作用.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆