Vue,动态导入模板

时间:2020-09-10 14:13:31

标签: javascript vue.js

我希望能够根据数据属性或prop换出组件的模板。这可能吗?

这是我的想法,但这当然行不通。

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

当前出现此错误:

无效的模板选项:[对象模块]

2 个答案:

答案 0 :(得分:1)

尝试require("./Themes/Templates/Default.vue")

更新

Default.vue中:

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

index.vue中的

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

    return {
        temp: Default
    }
}
...

答案 1 :(得分:1)

使用vue.js提供的component

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