安装vuex
在终端输入以下命令进行安装
npm i vuex -S
如果你的vue是2那么安装vuex就得高一个版本那就是vuex3,例如
npm install vuex@3
store文件中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
router文件中index.js
重要!!!
记得在main.js中new Vue中引入store
//路由守卫
router.beforeEach((to,from,next) =>{
localStorage.setItem("currentPathName",to.name) //设置当前路由的名称
store.commit("setPath") //出发store的数据更新
next()
})
store路由的使用
在自己的header文件中写入方法(说白了就是你在那个文件中使用路由就在那个文件中写)
computed:{
currentPathName(){
return this.$store.state.currentPathName; //需要监听的数据
}
},
watch: { //监听路由变化
currentPathName(newval , oldval){
console.log(newval)
}
},
到此就结束了,可以实时监听路由,然后根据自己的需要去操作