vue3+vue-router动态路由设置与面包屑实现

1.添加组件vue-router

yarn add vue-router

2.动态路由添加

创建文件/router/index.ts

import { createRouter, createWebHashHistory, RouteLocationNormalized, RouteRecordRaw } from 'vue-router';
import { Session } from '@/utils/storage';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { HOME_NAME,LOGIN_PATH } from '@/utils/constant';
import { useMenuStore } from '@/stores/menu';
import staticRoutes from './static';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...staticRoutes],
});

async function canUserAccess(_to:RouteLocationNormalized){
	const token = Session.get('token');
	return !!token;
}


/**
 * 动态添加路由
 * @param {*} parentName
 * @param {*} menus
 */
const addRoutes = (parentName: string,menus: MenuInfo[] = [])=> {
	const parentRouter: RouteRecordRaw = {path: '',name: parentName,children:[]};

	menu2Routes( parentRouter, menus);
	const pr = router.getRoutes().find(v=>v.name== parentName);
	if(pr){
		pr.children = parentRouter.children;
		router.addRoute(pr);
	}
}

/**
 * 菜单转路由列表
 * @param {*} parentRouter
 * @param {*} menus
 */
const menu2Routes = (parentRouter: RouteRecordRaw, menus: MenuInfo[] = [])=>{
	menus.forEach((info)=>{
		const newRouter = {
			path: info.path,
			name: info.name,
			children:[],
			meta:{title: info.title}
		};
		if(info.children && info.children.length==0){
			newRouter.component =()=>import(`/src/views/modules${ info.path }/index.vue`);
		} 

		parentRouter?.children?.push( newRouter );
		
		if(info.children && info.children.length>0){
			menu2Routes(newRouter, info.children);
		}
	});
}

/**
 * 扩展router,添加刷新路由方法
 */
router.refreshRouters=()=>{
	//解决刷新界面路由重置问题
	const useMenu = useMenuStore();  
    //将菜单路由挂载到HOME_NAME静态路由下
	addRoutes(HOME_NAME, useMenu.menus);
	return router;
}

router.beforeEach(async (to, _from) => {
	NProgress.configure({showSpinner: false});
	NProgress.start();
	const canAccess = await canUserAccess(to);
	if (!canAccess && to.path !=LOGIN_PATH) return LOGIN_PATH;
})

router.afterEach((_to, _from, _failure) => {
	NProgress.done()

})


// 添加异常处理
const originalPush = router.push
router.push = (to) => {
  try {
    return originalPush(to)
	
  } catch (error) {
    window.console.log(`%c${ error }`, 'color:red')
    return originalPush({ name: '404' })
  }
}

// 导出路由
export default router;

静态路由文件/router/static.ts

import { RouteRecordRaw } from 'vue-router';
import { HOME_NAME,HOME_PATH, LOGIN_NAME,LOGIN_PATH,MENU_DEFAULT_ACTIVE } from '@/utils/constant';

const staticRoutes: Array<RouteRecordRaw> = [
	{
        path: '/',
        redirect: MENU_DEFAULT_ACTIVE,
    },
	{
		path: HOME_PATH,
		name: HOME_NAME,
		component: () => import('@/views/home/index.vue'),
		meta: {
			title: '主页',
		},
		children:[],
	},
	{
		path: LOGIN_PATH,
		name: LOGIN_NAME,
		component: () => import('@/views/login/index.vue'),
		meta: {
			title: '登录',
		},
	},
	
	{
		path: '/:path(.*)*',
		name: 'notFound',
		component: () => import('@/views/error/404.vue'),
		meta: {
			title: '找不到此页面',
		},
	},
	{
		path: '/401',
		name: 'noPermission',
		component: () => import('@/views/error/401.vue'),
		meta: {
			title: '没有权限',
		},
	},
];

export default staticRoutes;

3.使用动态路由

import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus';
import router from '@/router'
import i18n from '@/locale'

import 'element-plus/dist/index.css';
import './style.css'

const app = createApp(App)
//添加动态路由使用
//refreshRouters --解决刷新界面路由重置问题
app.use(router.refreshRouters());
app.use(i18n.loadDefault());
app.use(ElementPlus);
app.mount('#app')

4.添加面包屑

mkdir -p src\\views\\home\\components\\headbar\\components\\crumb

crumb目录下创建文件index.ts

<template>
  <el-breadcrumb separator="/" class="crumb-container flex">
    <transition-group name="right-in-out">
      <el-breadcrumb-item
        v-for="item in crumbs"
        :key="item.name">
        {{ item.meta?.title }}
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script setup lang="ts">
import {ref,watchEffect} from "vue"
import { useRoute, RouteRecordRaw } from 'vue-router'

const crumbs = ref<RouteRecordRaw[]>([]);
const route = useRoute();

const crumbHandle = ()=>{
	crumbs.value = []
    //读取路由信息
	route.matched.forEach((item) => {
		crumbs.value.push(item);
	});
	//因为是挂载主页路由下,所以去掉根节点
	crumbs.value.shift();
}


watchEffect(() => {
  crumbHandle()
})

</script>

<style lang="scss" scoped>

:deep(.el-breadcrumb__inner) {
  font-weight:bolder;
}

</style>

5.效果

  • 14
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue3中实现面包屑和路由跳转需要使用Vue Router和Vue Composition API。首先,我们需要在项目中安装Vue Router和创建路由配置。 1.安装Vue Router: 我们可以使用npm或者yarn来安装Vue Router ``` npm install vue-router ``` 2.创建路由配置: 在main.js中导入Vue Router,并创建路由实例,配置路由表和对应的组件。 ```javascript import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import Home from './components/Home.vue' import About from './components/About.vue' import Contact from './components/Contact.vue' const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, { path: '/contact', component: Contact } ] const router = createRouter({ history: createWebHistory(), routes }) createApp(App).use(router).mount('#app') ``` 3.实现面包屑导航: 在App.vue中,我们可以使用`$route`属性来获取当前路由信息,并使用`v-for`指令循环渲染面包屑导航。 ```vue <template> <div> <ul> <li v-for="crumb in crumbs" :key="crumb.path"> <router-link :to="crumb.path">{{ crumb.name }}</router-link> </li> </ul> <!-- 其他内容 --> <router-view></router-view> </div> </template> <script> export default { computed: { crumbs() { const matched = this.$route.matched return matched.map(route => ({ name: route.name, path: route.path })) } } } </script> ``` 在上面的代码中,我们使用`$route.matched`来获取与当前路径匹配的路由记录数组并遍历生成面包屑导航。每个导航都使用`router-link`组件渲染,并根据对应的路由记录设置路径和名称。 4.实现路由跳转: 要实现路由跳转,我们可以在模板中使用`router-link`组件,或者在JavaScript中使用Vue Router提供的编程式导航方法。 ```vue <template> <div> <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> <router-link to="/contact">Contact</router-link> <!-- 其他内容 --> <router-view></router-view> </div> </template> ``` 或者在JavaScript中使用编程式导航: ```javascript // 在Vue组件中 this.$router.push('/about') // 跳转到/about // 在普通JavaScript中 router.push('/about') // 跳转到/about ``` 以上就是使用Vue3和Vue Router实现面包屑导航和路由跳转的基本步骤。通过配置路由表和使用Vue Router提供的组件和API,我们可以轻松地实现面包屑导航和路由跳转功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Oscar_0208

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值