简体   繁体   中英

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]

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

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,
  },
},
...

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