Importing vue template snippet results in [Object Promise]

Viewed 141

I'm trying to dynamically include a template snippet from another file into my SFC template, but where I'd like the markup to appear I only get [Object Promise]. I understand this is because import(…) returns a Promise, but I can't for the life of me figure out how to resolve it. I've tried simply putting it in the template and I've tried resolving it in a function (import(…).then((t) => t)). Doesn't make any difference. Minimal example follows.

@/components/DynamicTemplateImport.vue:

<template>
  <div>
    <div
      v-for="(filename, idx) of templates"
      v-bind:key="idx"
    >
      {{ import(`@/templates/${filename}.vue`) }}
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class DynamicTemplateImport extends Vue {
  templates = ['Foo', 'Bar', 'Baz'];
}
</script>

@/templates/Foo.vue:

<template>
  <p>Foo</p>
</template>
2 Answers

You can create 3 component 'Foo', 'Bar' and 'Baz' then use <component :is="myDynamicComponent"></component> :

<template>
  <div>
    <component :is="myDynamicComponent"></component>
  </div>
</template>

<script>
export default {
  computed: {
    myDynamicComponent() {
      if (// Foo wanted) {
        return () => import('@/components/Foo');
      } else if (// Bar wanted) {
        return () => import('@/components/Bar');
      } else if (// Baz wanted) {
        return () => import('@/components/Baz');
      }
    },
  },
};
</script>
<template>
  <div id="app">
    <component v-for="(c, i) in comp" :is="getComponent(c)" :key="i" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      comp: ["Foo", "Bar", "Baz"],
    };
  },
  methods: {
    getComponent(name) {
      return () => import(`./components/${name}.vue`);
    },
  },
};
</script>
Related