vuex安装
npm i vuex -S
store.js的引入
在src目录下建立一个store文件夹引入js文件
store.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
main.js中引入vuex
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
router/index.js中映入vuex
import store from "@/store";
//设置路由守卫
router.beforeEach((to, from, next) => {
localStorage.setItem("currentPathName", to.name) // 设置当前的路由名称,为了在Header组件中去使用
store.commit("setPath") // 触发store的数据更新
next() // 放行路由
})
在页面中使用
Header.vue
<script>
computed: {
currentPathName () {
return this.$store.state.currentPathName; //需要监听的数据
}
},
watch: {
currentPathName (newVal, oldVal) {
console.log(newVal)
}
},
</script>
// 使用 ,放在页面中
<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>