Main.js
var routeList = []; router.beforeEach((to, from, next) => { var index = -1; for(var i = 0; i < routeList.length; i++) { if(routeList[i].name == to.name) { index = i; break; } } if (index !== -1) { //如果存在路由列表,則把之后的路由都刪掉 routeList.splice(index + 1, routeList.length - index - 1); } else if(to.name != '登錄'){ routeList.push({"name":to.name,"path":to.fullPath}); } to.meta.routeList = routeList; next() });
2、在要使用的組件中
<template> <div class="level-bread"> <el-breadcrumb separator="/"> <el-breadcrumb-item v-for="item in realList" :to="item.path">{{item.name}}</el-breadcrumb-item> </el-breadcrumb> </div> </template> <script> export default { name: "lelve-bread", created(){ this.getRoutePath(); }, data() { return { realList: [] } }, methods:{ getRoutePath() { this.realList = this.$route.meta.routeList; } }, beforeRouteEnter(to,from, next) { next((vm) => { vm.realList = to.meta.routeList; }); }, // watch:{ // $route:function(newV,oldV) { // this.realList =newV.meta.routeList; // } // } } </script>
用 watch 或者 beforeRouteEnter 均可。
需要注意的是,beforeRouteEnter 此時(shí)訪問(wèn)不到this。
const Foo = { template: `...`, beforeRouteEnter (to, from, next) { // 在渲染該組件的對(duì)應(yīng)路由被 confirm 前調(diào)用 // 不!能!獲取組件實(shí)例 `this` // 因?yàn)楫?dāng)守衛(wèi)執(zhí)行前,組件實(shí)例還沒(méi)被創(chuàng)建 }, beforeRouteUpdate (to, from, next) { // 在當(dāng)前路由改變,但是該組件被復(fù)用時(shí)調(diào)用 // 舉例來(lái)說(shuō),對(duì)于一個(gè)帶有動(dòng)態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時(shí)候, // 由于會(huì)渲染同樣的 Foo 組件,因此組件實(shí)例會(huì)被復(fù)用。而這個(gè)鉤子就會(huì)在這個(gè)情況下被調(diào)用。 // 可以訪問(wèn)組件實(shí)例 `this` }, beforeRouteLeave (to, from, next) { // 導(dǎo)航離開(kāi)該組件的對(duì)應(yīng)路由時(shí)調(diào)用 // 可以訪問(wèn)組件實(shí)例 `this` } }
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com