【问题标题】:Vue dynamic component template not working for promiseVue动态组件模板不适用于承诺
【发布时间】:2021-07-22 06:57:19
【问题描述】:
<template>
  <component :is="myComponent" />
</template>

<script>
export default {
  props: {
    component: String,
  },

  data() {
    return {
      myComponent: '',
    };
  },

  computed: {
    loader() {
      return () => import(`../components/${this.component}`);
    },
  },

  created() {
    this.loader().then(res => {
      // components can be defined as a function that returns a promise;
      this.myComponent = () => this.loader();
    },
  },
}
</script>

参考:

https://medium.com/scrumpy/dynamic-component-templates-with-vue-js-d9236ab183bb

Vue js import components dynamically

控制台抛出错误“this.loader() 不是函数”或“this.loader().then”不是函数。

【问题讨论】:

  • 尝试将 loader() 从计算属性更改为方法。

标签: vue.js vue-dynamic-components


【解决方案1】:

不确定您为什么会看到该错误,因为 loader 被明确定义为返回函数的计算道具。

但是,created 钩子似乎调用了两次loader()(第二次调用是不必要的)。这可以简化:

export default {
  created() {
    // Option 1
    this.loader().then(res => this.myComponent = res)

    // Option 2
    this.myComponent = () => this.loader()
  }
}

demo 1

更简单的方法是将loader 重命名为myComponent,去掉myComponent 数据属性:

export default {
  //data() {
  //  return {
  //    myComponent: '',
  //  };
  //},

  computed: {
    //loader() {
    myComponent() {
      return () => import(`../components/${this.component}`);
    },
  },
}

demo 2

【讨论】:

  • 谢谢!这是 2.0 演示。我发现我们需要在 3.0 中再添加一件事。 this.myComponent = shallowRef(defineAsyncComponent(() => this.loader()));
猜你喜欢
  • 1970-01-01
  • 2020-12-06
  • 2015-04-18
  • 2019-11-01
  • 2018-01-06
  • 1970-01-01
  • 2012-04-26
  • 2017-03-20
  • 2015-07-26
相关资源
最近更新 更多