多标签vuex

发布时间 2023-11-09 13:41:26作者: 年轻浅识

vuex只有在第一次打开页面或页面刷新时会初始化,不受页面生命周期影响。
在vue打开多标签页面共享vuex时,多个页面vuex单独不受影响,所以如果某个页签修改了vuex的值,其他页签并不会同步修改。

多页签同步vuex的思路:监听页签选中状态,选中时判断当前vuex同步值与本地存储值,不相同调用mutations方法更新vuex即可。

SET_INFO (state) {
    state.userInfo = {
        name:cookie.getCookie('name'),
        token:cookie.getCookie('token')
    }
},
created() {
  document.addEventListener('visibilitychange', this.handleVisiable)
},
destroyed() {  
  document.removeEventListener('visibilitychange', this.handleVisiable)  
},
methods: {
  handleVisiable(e) {
    if(e.target.visibilityState=='visible'){
      if(this.token!=cookie.getCookie('token')){
        this.$store.commit('SET_INFO')
      }
    }
  },
}