首先在router的index.js中加入
import store from './store'
Vue.use(VueRouter)
// 路由守卫
router.beforeEach((to, from, next) => {
localStorage.setItem("currentPathName", to.name) // 设置当前的路由名称,为了在Header组件中去使用
store.commit("setPath") // 触发store的数据更新
next() // 放行路由
})
export default router
安装vuex后在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
在Header.Vue中
<template>
<div style="flex: 1;">
<span :class="collapseBtnClass" style="cursor: pointer; font-size: 18px" @click="collapse()"></span>
<el-breadcrumb separator="/" style="display: inline-block; margin-left: 10px">
<el-breadcrumb-item :to="'/'">首页</el-breadcrumb-item>
<el-breadcrumb-item>{{ currentPathName }}</el-breadcrumb-item>
</el-breadcrumb>
</div>
</template>
<script>
computed: {
currentPathName() {
return this.$store.state.currentPathName; //需要监听的数据
}
},
watch: {
currentPathName(newVal, oldVal) {
console.log(newVal)
}
},
</script>
效果