VUE3 使用资源路径加载

1.使用场景

有些情况下,我需要使用组件路径动态的方式加载组件。

2.实现方法

import { defineAsyncComponent } from 'vue';

/**
 * 根据view组件路径异步加载组件.
 * @param {String} view 组件路径 这个文件在views 下.
 * @returns {*}
 */
AppUtil.loadComponent=function (view){
    const modules = import.meta.glob('@/views/**/*.vue');
    let path="/src/views/" +view;
    return defineAsyncComponent( modules[path]);
}

我们可以看到上面的代码,他的作用传入一个组件的路径,通过 import.meta.glob 方法加载目录和组件的映射,我们可以看到虽然使用了通配符,但实际上这个方法执行起来并不慢。
这个我们可以看到这个方法变成下面这样
image

可以发现实际编译成了一个map对象

{path:()=>{}}

我们通过 传入的路径,得到异步得组件对象。

3.动态加载组件得例子

<template>
    <div>
        <component :is="view" ></component>
        <a-button @click="loadView">loadView</a-button>
    </div>
</template>
<script>
import component1 from "./component1.vue";
import AppUtil from "../../../assets/js/AppUtil";
export default {
    name: "dynamicComponent",
    components: {
        "component1":component1
    },
    data() {
        return {
            view: "component1"
        }
    },
    methods:{
        loadView(){
            let component = AppUtil.loadComponent('modules/demo/component2.vue') ;
            this.view=component;
        }
    }
}
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章