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

L Frank
  • 3
  • 4

1 Answers1

0

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

tony19
  • 125,647
  • 18
  • 229
  • 307
  • Thank you! This is 2.0 demo. I found we need add one more thing in 3.0. this.myComponent = shallowRef(defineAsyncComponent(() => this.loader())); – L Frank Apr 29 '21 at 16:26