Vue3.0 使用route手寫面包屑導(dǎo)航組件
如圖,實現(xiàn)一個點擊左側(cè)菜單后,右側(cè)面包屑導(dǎo)航隨之變化的功能。
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可以存在多個,也可以合并。文中只監(jiān)聽了一個數(shù)據(jù),故只使用了一個watch。
// watch()中可以放置兩個參數(shù),第一個參數(shù)放入被監(jiān)聽數(shù)據(jù),第二個參數(shù)放入回調(diào)函數(shù)用來進行數(shù)據(jù)操作
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: '數(shù)據(jù)統(tǒng)計'
},
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: '用戶統(tǒng)計'
},
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> <!--避免在導(dǎo)航最后出現(xiàn)分割線-->
</router-link>
</a>
</li>
</ul>
</div>
</template>
Js部分
route.matched中的信息
image.png
- 定義一個數(shù)組list:[] 用來存放路由中的信息
- list數(shù)組中的數(shù)據(jù)不會在點擊菜單后自動變化,需要用watch監(jiān)聽數(shù)組變化并更新數(shù)據(jù)
/ 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;//獲取菜單對應(yīng)的路由信息
state.list = matched;
})
//watch
watch(()=>route.matched,(newVal,oldVal)=>{
let matched = newVal;
state.list = matched;//更新路由菜單數(shù)組
})
//return
return {
...toRefs(state), //toRefs() 將數(shù)據(jù)變成響應(yīng)式數(shù)據(jù)
};
}
};
</script>