简体   繁体   中英

Vue dynamic component template not working for 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>

Reference:

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

Vue js import components dynamically

Console throw error "this.loader() is not a function" or "this.loader().then" is not a function.

Not sure why you're seeing that error, as loader is clearly defined as a computed prop that returns a function.

However, the created hook seems to call loader() twice (the second call is unnecessary). That could be simplified:

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

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

demo 1

Even simpler would be to rename loader with myComponent , getting rid of the myComponent data property:

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

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

demo 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM