nuxt 利用Vuex控制状态 切换城市以及切换城市之后跳转首页遇到的坑
- 在 切换城市的VUE 组件中
handleSelect: function(item) {
const xzdCity = item.value
this.$store.commit('xzCity/changeCity',xzdCity)
this.$router.push('/')
// window.location.href = '/' /**这里是个坑***/
}
- 在 Vuex store 中
const state = ()=>( {xzdCity:''} )
const mutations = {
changeCity(state,val){
state.xzdCity = val
}
}
const actions = {
changeCity:({commit},xzdCity)=>{
commit('changeCity',xzdCity)
}
}
//解决不同模块命名冲突的问题,将不同模块的namespaced:true
//之后在不同页面中引入getter、actions、mutations时,需要加上所属的模块名
export default {
namespaced:true,
state,
actions,
mutations
}
在这里 遇到的坑是点击切换城市之后,页面会重新刷新,刚开始使用的是
window.location.href = '/'
跳转到首页 ,从VUE 的开发工具中也能看到 state
值得变化,但是在切换 Vuex 中的state 的时候会清空,后来打算将 其切换的值存放到 window.localStorage
中,但是由于是 nuxt SSR
服务端渲染 所以 会报错
最后解决这个坑 是将
this.$router.push('/') //换成这个就可以了
// window.location.href = '/' /**这里是个坑***/