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 方法加載目錄和組件的映射,我們可以看到雖然使用了通配符,但實際上這個方法執行起來並不慢。
這個我們可以看到這個方法變成下面這樣
可以發現實際編譯成了一個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>