Vue3.0 使用route手写面包屑导航组件
如图,实现一个点击左侧菜单后,右侧面包屑导航随之变化的功能。
image.png
image.png
vue3 router 官方英文文档
vue3 router API 移步: https://next.router.vuejs.org/
一些需要注意的点
- route
在vue3中,route不可直接使用,需要引入useRoute,再用一个变量去接收。
// script 引入useRoute
import {useRoute} from 'vue-router';
//setup 中接收route
const route = useRoute();
- watch
在vue3中,watch可以存在多个,也可以合并。文中只监听了一个数据,故只使用了一个watch。
// watch()中可以放置两个参数,第一个参数放入被监听数据,第二个参数放入回调函数用来进行数据操作
watch(()=>route.matched,(newVal,oldVal)=>{
// xxx= newVal;
})
router部分
为每一个路由配置一个meta:{title:" xxx"}
//index.js
import { createRouter, createWebHashHistory } from "vue-router";
const routes = [
{
path: "/index",
name: "index",
meta: {
title: '主页'
},
redirect: '/main',
component: () => import(/* webpackChunkName: "index" */ "../views/layout/index.vue"),
children: [
{
path: "/main",
name: "main",
meta: {
title: '首页'
},
//component: () => import(/* webpackChunkName: "index" */ "../views/layout/home/main.vue")
component: () => import(/* webpackChunkName: "index" */ "../views/layout/home/main.vue")
},
{
path: "/stats",
name: "stats",
meta: {
title: '数据统计'
},
component: () => import(/* webpackChunkName: "index" */ "../views/layout/stats/stats.vue")
},
{
path: "/wms",
name: "wms",
meta: {
title: '信息管理'
},
component: () => import(/* webpackChunkName: "index" */ "../views/layout/wms/wms.vue"),
children: [
{
path: "/wms/list",
name: "list",
meta: {
title: '列表展示'
},
component: () => import(/* webpackChunkName: "index" */ "../views/layout/wms/list.vue")
},
{
path: "/wms/info",
name: "info",
meta: {
title: '用户统计'
},
component: () => import(/* webpackChunkName: "index" */ "../views/layout/wms/info.vue")
},
]
}
]
},
];
Html部分
// An highlighted block
<template>
<div class="breadcumb">
<ul>
<li >
<a v-for="(item,index) in list" :key="index">
<router-link :to="{path:item.path}">{{item.meta.title}}
<span v-if="index < list.length-1">/ </span> <!--避免在导航最后出现分割线-->
</router-link>
</a>
</li>
</ul>
</div>
</template>
Js部分
route.matched中的信息
image.png
- 定义一个数组list:[] 用来存放路由中的信息
- list数组中的数据不会在点击菜单后自动变化,需要用watch监听数组变化并更新数据
/ An highlighted block
<script>
import { reactive, toRefs, onMounted,watch } from "vue";
import {useRoute} from 'vue-router';
export default {
setup() {
//data
const route = useRoute();
const state = reactive({
list:[]
});
//onMounted
onMounted(()=>{
let matched = route.matched;//获取菜单对应的路由信息
state.list = matched;
})
//watch
watch(()=>route.matched,(newVal,oldVal)=>{
let matched = newVal;
state.list = matched;//更新路由菜单数组
})
//return
return {
...toRefs(state), //toRefs() 将数据变成响应式数据
};
}
};
</script>
网友评论