利用获取路由参数实现动态的更新面包屑

1、下载vuex

npm i vuex -S

2、在vue项目的src下建立包store,并创建index.js

index,js

import Vue from 'vue'
import Vuex from 'vuex'


Vue.use(Vuex)


const store = new Vuex.Store({
    state:{
        currentPathName:''
    },
    mutations:{
        setPath(state){
            state.currentPathName = localStorage.getItem("currentPathName")
        }
    }
})


export default store

3、在main.js中引入store

4、在router包下的index.js下添加路由守卫


//路由守卫
router.beforeEach((to, from , next ) =>{
  localStorage.setItem("currentPathName",to.name)  //设置当前路由名称
  index.commit("setPath")  //触发store的数据更新
  next()   //放行路由
})

注意要引入store

5、在面包屑导航组件获取需要监听的数据

即使用面包屑的地方使用computed和watch(可以不用)

    computed:{
            currentPathName(){
                return this.$store.state.currentPathName;  //需要监听的数据
            }
        },
        watch:{  //监听路由变化
            currentPathName(newVal,oldVal){
                console(newVal)
            }

        },

面包屑部分,使用currentPathName拿到值

<!--        页签-->
        <el-breadcrumb separator="/"  class="ml-10" style="display:inline-block">
            <el-breadcrumb-item :to="'/'" >首页</el-breadcrumb-item>
            <el-breadcrumb-item >{{currentPathName}}</el-breadcrumb-item>
        </el-breadcrumb>

router包下的index.js参考,为了简便直接使用name做页签

const routes = [
  {
    path: '/',
    component: () => import( '../views/Manage.vue'),
    redirect:"/home",
    children:[
      {
        path:"home",name:"首页",component: () => import('../views/Home.vue'),

      },
      {
        path:"user",name:"用户管理",component: () => import('../views/User.vue'),
      },
    ]
  },

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐