Vue 动态组件模板不适用于 promise

问题描述

<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() is not a function”或“this.loader().then” is not a function。

解决方法

不确定您为什么会看到该错误,因为 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...