Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

能否在vue中使用import()函数来引入子组件并注册?

普通的注册组件是

import ComA from './ComA'

export default { 
    components: { 
        ComA,
    }, 
}

或者使用异步组件

export default { 
    components: { 
        ComA: () => import('./ComA')
    }, 
}

那请问是否能在组件运行时通过 import() 函数去引入和注册组件呢?类似下面的写法

mounted(){
    import('./ComA').then(com => {
        //在此通过引入的com来注册组件呢?
    })
}

谢谢!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

可以用动态组件 https://cn.vuejs.org/v2/guide/components.html#动态组件

<tempalte>
    <component :is="currentComponent"></component>
</template>
<script>
export default {
    data: {
        currentComponent: ''
    },
    mounted() {
        this.currentComponent = 'com-b';
    },
    components: {
        'com-a': () => import('./A'),
        'com-b': () => import('./B'),
    }
    
}
</script>

你要愿意注册到全局也可以:

<tempalte>
    <button @click="clicked">加载组件</button>
    <div v-if="currentComponent">
        <component :is="currentComponent"></component>
    </div>
</template>
<script>
export default {
    data: {
        currentComponent: ''
    },
    methods: {
        clicked() {
            import('./A').then(A => {
                Vue.component('com-a',A);
                this.currentComponent = 'com-a';
            });
        }
    }
    
}
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...