Javascript动态模块导入包含变量的问题

时间:2019-05-28 14:28:29

标签: javascript vue.js import

好的,所以我一直把头撞在墙上,试图弄清楚这到底是怎么回事。看,我一直在尝试在Vue.js中动态加载模块。让我感到困惑的是,以下内容确实有效(即当我对模块的路径进行硬编码时):

currentModal(){
    return () => System.import(`../../ride/modals/boarding.vue`);
},

但是,如果我这样做:

currentModal(){
    let path = "../../ride/modals/";
    return () => System.import(`${path}boarding.vue`);
},

我收到以下错误:

  

找不到模块'../../ ride / modals / boarding.vue'。

然后,如果我反过来做:

currentModal(){
    let content = "boarding.vue";
    return () => System.import(`../../ride/modals/${content}`);
}, 

错误变为:

  

渲染错误:“ TypeError:未定义不是函数”

很明显,当我使用变量而不是对路径进行硬编码时,有所不同...但是对于我一生来说,我不知道是什么。有任何线索吗?

1 个答案:

答案 0 :(得分:0)

正如Bergur在他的评论中提到的那样,问题确实是webpack无法解析尚不存在的字符串(问题在{{3}}中进行了解释)。相反,我要做的是在我的组件中添加一个称为“内容列表”的属性,然后在主页中用所需的组件填充它,如下所示:

父组件:

<template>

    .....

    <modal-window   
                    :init-visible="modalVisible"
                    :content-list="contentList"
                    @modalClosed="modalClosed">
    </modal-window>

    .....

</template>

<script>
    import mainContent from './modals/main.vue';  //I doubt this is still useful
    import otherContent from './modals/other.vue'; //I doubt this is still useful


    export default{
        data(){
            return {

                modalVisible: false,

                contentList: {
                    main:       () => System.import("./modals/main.vue"),
                    other:      () => System.import("./modals/other.vue")
                },
            }
        },
    }

</script>

在模式组件内部:

<template>

    ...


    <div ref="scrolling-pane" class="scrolling-pane" :class="{ 'scrolling-pane-normal': !isDirty, 'scrolling-pane-dirty': isDirty }" key="b">
        <transition name="content-slide"
                    :enter-active-class="enterClassName"
                    :leave-active-class="leaveClassName"
                    @before-enter="beforeEnter" 
                    @before-leave="beforeLeave"
                    @after-enter="afterEnter"
                    @after-leave="afterLeave">

            <keep-alive>
                <component :is="currentModal" @switchContent="onSwitchContent"></component>
            </keep-alive>
        </transition>
    </div>

    ...

</template>

<script>

export default{
        components: {
        },

        props: {
            initVisible: Boolean,
            contentList: Object
        },
        data(){
            return {
                currentContent: this.contentList['main']
            }
        }

        ...

</script>