Vue.js - load component from ajax call

2019-07-13 11:46发布

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>

1条回答
时光不老,我们不散
2楼-- · 2019-07-13 12:25

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>
查看更多
登录 后发表回答