Martyn Ball
Martyn Ball

Reputation: 4885

Vue, dynamically import template

I want to be able to swap out a template for a component based on a data property, or a prop. Is this possible?

This is my idea, however this doesn't work of course.

./index.vue

export default {
    props:{

    },
    template: import(`./Themes/Templates/${this.template}`),
    data: function() {
        return {
            template: 'Default'
        }
    },

./Themes/Templates/Default.vue

<div>
    <p>Default template</p>
</div>

Currently getting this error:

invalid template option:[object Module]

Upvotes: 1

Views: 126

Answers (2)

Syed
Syed

Reputation: 16513

Use component that vue.js provide:

<template>
  <component :is="myComp"></component>
</template>

...
// You need to import all the possible components
import CompOne from '/CompOne.vue';
import CompTwo from '/CompTwo.vue'

props:{
  myComp: {
    default: 'comp-one',
    type: String,
  },
},
...

Upvotes: 1

Maverick Fabroa
Maverick Fabroa

Reputation: 1173

Try require("./Themes/Templates/Default.vue")

Update:

In Default.vue:

...
export default {
    name: "Default"
}
...

and in index.vue:

...
template: this.temp,
data() {
    const { Default } = import("./Themes/Templates/Default.vue");

    return {
        temp: Default
    }
}
...

Upvotes: 1

Related Questions