vue 2.0 + elementUI 實現麪包屑導航欄

Main.jshtml

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()
});

二、在要使用的組件中vue

<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 此時訪問不到this。segmentfault

官網描述 https://router.vuejs.org/zh-c...this

const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染該組件的對應路由被 confirm 前調用
    // 不!能!獲取組件實例 `this`
    // 由於當守衛執行前,組件實例還沒被建立
  },
  beforeRouteUpdate (to, from, next) {
    // 在當前路由改變,可是該組件被複用時調用
    // 舉例來講,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
    // 因爲會渲染一樣的 Foo 組件,所以組件實例會被複用。而這個鉤子就會在這個狀況下被調用。
    // 能夠訪問組件實例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 導航離開該組件的對應路由時調用
    // 能夠訪問組件實例 `this`
  }
}

參考資料:
https://router.vuejs.org/zh-c...
https://segmentfault.com/q/10...code

相關文章
相關標籤/搜索