【问题标题】:Vue.js - load component from ajax callVue.js - 从 ajax 调用加载组件
【发布时间】:2017-11-16 16:45:06
【问题描述】:

我正在尝试从 api 数据呈现或加载组件。为了解释更多,假设我有测试组件,我将它直接注入到我的父组件中,它可以工作。但是,当我尝试将组件标记保存在数据库中并运行 ajax 调用时,我的组件标记显示但不起作用,或者更确切地说是加载/渲染。请帮忙。

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

【问题讨论】:

    标签: api vue.js vuejs2 vue-component axios


    【解决方案1】:

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

    如果您只是想指定组件类型,可以使用dynamic component。在您的情况下,它可能看起来像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 2015-06-26
      • 2019-06-05
      • 1970-01-01
      • 2021-07-14
      • 2018-03-13
      相关资源
      最近更新 更多