天天報道:vue + Element UI 動態Breadcrumb 面包屑的制作

2023-01-04 17:12:48 來源:51CTO博客


(相關資料圖)

效果


面包屑用于顯示當前頁面的路徑,快速返回之前的任意頁面。

一、路由配置

代碼如下:

import Vue from "vue"import VueRouter from "vue-router"Vue.use(VueRouter)const VueRouterPush = VueRouter.prototype.pushVueRouter.prototype.push = function push(to) {  return VueRouterPush.call(this, to).catch(err => err)}const routes = [  {     path: "/",     component: ()=>import("@/views/LoginView")   },  {     path: "/login",     name: "login",    component: ()=>import("@/views/LoginView"),  },  {    path: "/home",    name:"home",    component: ()=>import("@/views/HomeView"),    meta:{      title:"首頁",      path:"/home"    },    children: [      { //主頁        path: "/home",         component: ()=>import("@/views/main/MainView"),        meta:{          title:"",          path:"/home"        }      },       { //個人信息        path: "userinfo",         component: ()=>import("@/views/userinfo/UserInfo"),         meta:{          title:"個人中心",          path:"/userinfo"        }      },        { //分析頁        path: "analyse",         component: ()=>import("@/views/Analyse"),        meta:{          title:"分析頁",          path:"/analyse"        }      },      ]  }]const router = new VueRouter({  routes})export default router

這里使用了router的meta屬性,為其設置名為title的屬性,用來當作面包屑的展示名稱,當然,也可以直接使用路由的name屬性。

二、使用步驟

1.Breadcrumb.vue:

代碼如下:

<script>export default {  data() {    return {      breadList: [],    };  },  watch: {    $route() {//監聽$route      this.getBreadcrumb();    },  },  methods: {    isHome(route) {      return route.name === "home";    },    getBreadcrumb() {      let matched = this.$route.matched;      //如果不是首頁      if (!this.isHome(matched[0])) {        matched = [].concat(matched);      }      this.breadList = matched;    },  },  created() {    //生命周期中調用獲取數據的方法    this.getBreadcrumb();  },};</script>

2.在頁面中使用

代碼如下:

<script>// 導入ScreenFull組件,控制全屏import FullScroll from "@/components/Header/ScreenFull.vue"http:// 導入頭像組件import Avatar from "@/components/Header/AvatarHeader.vue"http:// 導入面包屑import BreadVue from "../components/Bread.vue"export default {  components: {    FullScroll,    Avatar,    BreadVue  },  data(){    return{      breadList:null,    }  },}</script>

總結

文件目錄

vue-router和breadcrumb面包屑結合,實現展示當前路徑下的路由信息。關鍵是利用route對象的matched屬性,得到前匹配的路徑中所包含的所有片段所對應的配置參數對象數組,然后遍歷數組,并利用數組中對象的信息,展示到面包屑中。每個對象的path屬性為其對應的路由路徑,meta屬性為其元數據對象。

標簽: 數據對象 當前路徑 生命周期

上一篇:通訊!iOS不上架怎么安裝
下一篇:Typora下載安裝教程