【问题标题】:Vue, dynamically import templateVue,动态导入模板
【发布时间】:2020-12-29 01:30:51
【问题描述】:

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

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

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

目前出现此错误:

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

【问题讨论】:

    标签: javascript vue.js


    【解决方案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,
      },
    },
    ...
    

    【讨论】:

    • 谢谢,我做了类似的事情,但是动态导入了模板。
    • 如何调整它以应用于动态 html 模板,而不是导入整个 .vue 文件?我正在尝试解决:stackoverflow.com/questions/67786214/…
    【解决方案2】:

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

    【讨论】:

    • 这给了我以下错误:invalid template option:[object Module]
    猜你喜欢
    • 2019-03-06
    • 2019-04-23
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2019-02-03
    • 2020-03-16
    • 2020-12-09
    相关资源
    最近更新 更多