【问题标题】:Vue2 create component based on dataVue2基于数据创建组件
【发布时间】:2020-12-21 07:17:30
【问题描述】:

我想创建一个基于 ajax api 响应或数据的组件,其中包括:

  1. 模板
  2. 数据
  3. 方法 - 可能有多种方法

备注:响应或数据是动态的,不保存在文件中。

我尝试生成并返回结果,例如:

<script>
        Vue.component('test-component14', {
            template: '<div><input type="button" v-on:click="changeName" value="Click me 14" /><h1>{{msg}}</h1></div>',
            data: function () {
                return {
                    msg: "Test Componet 14 "
                }
            },
            methods: {
                changeName: function () {
                    this.msg = "mouse clicked 14";
                },
            }
        });

</script>

然后编译上面的代码:

axios.get("/api/GetResult")
    .then(response => {
        comp1 = response.data;
        const compiled = Vue.compile(comp1);
        Vue.component('result-component', compiled);
    })
    .catch(error => console.log(error))

Vue.compile(comp1) 出现错误 -

  • 模板应该只负责将状态映射到 UI。避免在模板中放置带有副作用的标签,例如

提前致谢

【问题讨论】:

  • /api/GetResult 返回了什么?
  • 返回是代码的第一部分-&lt;script&gt; Vue.component('test-component14', { ... &lt;/script&gt;,这是一个完整的组件。

标签: vuejs2 vue-dynamic-components async-components


【解决方案1】:

您的 Api 应该返回一个 JSON,其中包含 Vue 组件所需的每个属性(名称、数据、模板、方法),请注意,方法需要转换为实际的 js 函数(请查看docs

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: '#app',
  data() {
    return {
      apiComponent: { template: '<div>Loading!</div>' }
    };
  },
  methods: {
    loadApiComponent() {
      setTimeout(() => {
        this.buildApiComponent(JSON.parse('{"name":"test-component14","template":"<div><input type=\\\"button\\\" v-on:click=\\\"changeName\\\" value=\\\"Click me 14\\\" /><h1>{{msg}}</h1></div>","data":{"msg":"Test Componet 14 "},"methods":[{"name":"changeName","body":"{this.msg = \\\"mouse clicked 14\\\";}"}]}'));
      }, 2000);
    },
    buildApiComponent(compObject) {
      const {
        name,
        template,
        data,
        methods
      } = compObject;

      const compiledTemplate = Vue.compile(template);

      this.apiComponent = {
        ...compiledTemplate,
        name,
        data() {
          return { ...data
          }
        },
        methods: methods.reduce((c, n) => {
          c[n.name] = new Function(n.body);
          return c;
        }, {})
      };
    }
  },
  mounted() {
    this.loadApiComponent();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <component :is="apiComponent" />
</div>

【讨论】:

  • 谢谢。这看起来不错的样子。我只是好奇是否可以返回 Vue SFC 或 Vue.component 脚本?
  • 我觉得你可以看看SSR mode(服务器端渲染)
猜你喜欢
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 2022-09-29
  • 1970-01-01
相关资源
最近更新 更多