前期回顾
Vue3 + TS + Vite —— 大屏可视化 项目实战_vue3可视化大屏_彩色之外的博客-CSDN博客大屏可视化项目实战_vue3可视化大屏https://blog.csdn.net/m0_57904695/article/details/131014666?spm=1001.2014.3001.5501
目录
👍 动态组件
👀 动态路由
👍 动态组件
效果图:
代码示例:
<script lang="ts" setup>
import { defineAsyncComponent, ref } from 'vue';// 需要加载的组件集合
const components = ref(new Map<string, any>());
components.value.set('MyTag',defineAsyncComponent(() => import('./a.vue'))
);
components.value.set('Item',defineAsyncComponent(() => import('./b.vue'))
);// 默认加载的组件名
const compName = ref('MyTag');
// 组件切换
function onClick() {if (compName.value === 'MyTag') {compName.value = 'Item';} else {compName.value = 'MyTag';}
}
</script><template><div><el-button @click="onClick">改变组件</el-button><component :is="components.get(compName)"></component></div>
</template><style lang="scss" scoped></style>
👀 动态路由
import { createRouter, createWebHistory } from 'vue-router';
import axios from 'axios';const routes = [// 默认路由{path: '/',name: 'Home',component: () => import('@/views/Home.vue'),},
];const router = createRouter({history: createWebHistory(),routes,
});// 在路由跳转之前获取菜单数据并动态添加路由
router.beforeEach(async (to, from, next) => {// 判断是否已经获取到菜单数据if (router.getRoutes().length <= 1) {try {// 发起请求获取菜单数据const response = await axios.get('/api/menu');const menu = response.data;// 根据菜单数据动态生成路由generateRoutes(menu);// 添加新生成的路由router.addRoute(menu);// 继续路由跳转next({ ...to, replace: true });} catch (error) {console.error('无法获取菜单数据:', error);}} else {// 已经获取到菜单数据,继续路由跳转next();}
});// 根据菜单数据动态生成路由
function generateRoutes(menu) {menu.forEach((item) => {const route = {path: item.path,name: item.name,component: () => import(`@/views/${item.component}.vue`),};// 递归生成子路由if (item.children && item.children.length > 0) {route.children = generateRoutes(item.children);}routes.push(route);});
}export default router;