vue3,watch监控vuex里state值,遇到的奇怪问题?

问题描述:在制作多标签页时,发现奇怪bug
把getters.ts里activeView里的console.log给注释掉的话,就无法触发watch对activeView的监控;
如果把getters.ts里activeView里的console.log注释恢复的话,就能触发watch对activeView的监控;

1、把getters.ts里activeView里的console.log给注释掉的调试如下
增加路由
D:\vue3\src\store\appStore\getters.ts:16 getters下的: /submit
tab.vue:60 触发watch:activeView
tab.vue:61 newValue /submit
tab.vue:62 oldValue /dashboard
D:\vue3\src\store\appStore\getters.ts:16 getters下的: /submit

2、如果把getters.ts里activeView里的console.log注释恢复的调试如下
增加路由
一、VUEX的代码如下

1.state.ts文件:

export default {
    isCollapse: false,
    viewList: JSON.parse(window.sessionStorage.getItem('viewList')),
    activeView: JSON.parse(window.sessionStorage.getItem('activeView'))
}

2.mutations.ts文件:

export default {
    setIsCollapse(state: any, isCollapse: Boolean){
        state.isCollapse = isCollapse
    },
    setViewList(state: any, value: any){
        state.viewList = value
        window.sessionStorage.setItem('viewList', JSON.stringify(value))
    },
    setActiveView(state: any, value: any){
        state.activeView = value
        window.sessionStorage.setItem('activeView', JSON.stringify(value))
    },
}

3.getters.ts文件:

export default{
    isCollapse: (state: any) => state.isCollapse,
    viewList:(state: any) => {
        return JSON.parse(window.sessionStorage.getItem('viewList'))
    },
    activeView:(state: any) => {
        //把下面的注释掉,无法在watch里触发;取消注释,则能wathc到并触发
        //console.log("getters下的:",state.activeView)
        return JSON.parse(window.sessionStorage.getItem('activeView'))
    },
}
二、tab页面:

1.定义响应式的stores值

const stores = reactive({
  activeView:store.getters.activeView ? store.getters.activeView : '/dashboard',
  viewList:store.getters.viewList,
  worktabs:store.getters.viewList ? store.getters.viewList : [{name: 'home', title: '首页' ,path:'/dashboard'}]
})
// 监控activeView
watch(
    () => store.getters.activeView,
    (newValue,oldValue)=>{
      console.log("触发watch:activeView")
      console.log("newValue",newValue)
      console.log("oldValue",oldValue)

      stores.activeView = store.getters.activeView
    },{
      deep:true
    }
)

点击事件

// 增加路由
const addRoute = (value) => {
  // 选中高亮
  store.commit('setActiveView',value)
  console.log("增加路由")
}
阅读 3.4k
1 个回答

getters 响应式需要依赖 state 的更新,注释掉就没了依赖,不会触发响应

因为 setActiveView 是同时设置 state.activeViewsessionStorage,所以建议这里不用 getter 直接 store.state.activeView 即可,或把 getter 改成

activeView:(state: any) => state.activeView
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题