需要安装vuex:npm i vuex -S 安装vue-router:npm install vue-router -S
// Header.vue
<template>
<!--面包屑-->
<el-breadcrumb separator="/" style="display: inline-block; margin-left: 10px"> <!--行内块元素-->
<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>{{ currentPathName }}</el-breadcrumb-item>
</el-breadcrumb>
</template>
<script>
export default {
name: "Header",
computed:{
currentPathName(){
return this.$store.state.currentPathName //需要监听的数据
}
},
watch:{ //监听路由变化
currentPathName(newVal,oldVal){
console.log(newVal)
}
},
}
</script>
// router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Manage',
component: () => import('../views/Manage.vue'),
redirect:'/home',
children: [
{
path: 'home', name: '首页', component: () => import('../views/Home.vue')
},
{
path: 'user', name: '用户管理', component: () => import('../views/User.vue')
},
]
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
// 路由守卫
router.beforeEach((to,form,next)=>{
localStorage.setItem("currentPathName",to.name) //设置当前的路由名称
store.commit('setPath') //出发store的额数据更新
next() //放行
})
export default router
// store.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