vue3面包屑导航的制作
vue3,route.matched,面包屑导航
·
首先有固定的路由表
const routes:Array<RouteRecordRaw> =[
{
path: '/dashboard',
name:'dashboard',
meta: {
title:'首页',
icon: 'Watch'
}
},
{
path:'/system',//系统管理就是一个空的路径,点击系统管理不会跳转任何页面
name:'system',
meta: {
title: '系统管理',
icon: 'Menu',
roles: ['sys:manage']
},
children: [
{
path: '/department',
name:'department',
meta: {
title:'机构管理',
icon: 'ZoomOut',
roles: ['sys:dept']
}
},
{
path: '/userList',
name:'userList',
meta: {
title:'用户管理',
icon: 'ZoomOut',
roles: ['sys:user']
}
},
{
path: '/roleList',
name:'roleList',
meta: {
title:'角色管理',
icon: 'ZoomOut',
roles: ['sys:role']
}
},
{
path: '/menuList',
name:'menuList',
meta: {
title:'权限管理',
icon: 'ZoomOut',
roles: ['sys:menu']
}
}
]
},
{
path:'/goods',
name:'goods',
meta: {
title: '商品管理',
icon: 'ZoomOut',
roles: ['sys:goods']
},
children: [
{
path: '/goodCategory',
name:'goodCategory',
meta: {
title:'商品列表',
icon: 'ZoomOut',
roles: ['sys:goodCategory']
}
}
]
}]
route.matched
面包屑的思路就是需要得到访问路径的信息,比如title,可以得到一个数组,到时候渲染到面包屑标签里
需要用到route.matched,得到当前路径的匹配路径:比如点击商品管理,路径就是/goods/goodCategory。
matched,顾名思义就是匹配,/goods/goodCategory匹配到的路径就是/goods,/goodCategory:
匹配到的路径都是在route里声明过的
//利用route.matched可以得到单个匹配的路径
//路径会发生改变,所以要用watch进行监听
const getBreadCom = () => {
let mached = route.matched.filter(item => item.meta.title)
console.log(route.matched,mached)
// 第一个路径如果不是首页,需要在匹配路径前面拼接一个首页
const first = mached[0]
if(first.path != "/dashboard") {
mached = [{ path: '/dashboard',meta: {title: '首页'}} as any].concat(mached)
}
}
getBreadCom()
// 监听路径的改变,如果发生变化了,执行方法
watch(() =>route.path,() => getBreadCom())
类型转换
因为 当被点击后,需要把 to (目标路由的链接,类型都是RouteLocationRaw),传到router.push()里面
所以需要对 mached 进行类型的转换
import { ref,watch,Ref } from 'vue';
import { useRoute,RouteLocationMatched } from 'vue-router'
const route = useRoute()
// 定义导航数据,设置类型,否则赋值会报错
const tabs:Ref<RouteLocationMatched[]> = ref([])
const getBreadCom = () => {
let mached = route.matched.filter(item => item.meta.title)
console.log(route.matched,mached)
// 第一个路径如果不是首页,需要在匹配路径前面拼接一个首页
const first = mached[0]
if(first.path != "/dashboard") {
mached = [{ path: '/dashboard',meta: {title: '首页'}} as any].concat(mached)
}
//设置面包屑的数据
tabs.value = mached
}
getBreadCom()
// 监听路径的改变,如果发生变化了,执行方法
watch(() =>route.path,() => getBreadCom())
最后写在面包屑标签里
<template>
<el-breadcrumb separator="/">
<el-breadcrumb-item v-for="item in tabs" :to="item.path">{{item.meta.title}}</el-breadcrumb-item>
</el-breadcrumb>
</template>
更多推荐
已为社区贡献2条内容
所有评论(0)