3

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 Answer 1

6

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.