vue 学习日记(三)

vuex 状态管理,不同页面监听state值变化

尝试过用computed 和 watch去监听,结果无效,因为store是瞬时改变的,A页面改变值B页面接受改变值去执行方法,此时A页面改变的值B页面的state也是同时改变的,而且组件被销毁了,是不能够监听得到的,此方法只能用于组件都存在时候可用。

故使用组件路由守卫去监听,A页面改变值,进入B页面通过路由守卫beforeRouteEnter 监听并执行得到。

// 通过路由守卫,监听重新进入当前组件state的值
  beforeRouteEnter  (to, from, next) {
    next(vm => {
        // 通过 `vm` 访问组件实例
        if (!vm.userPoint) {
            axios.get(config.url_userIntegral).then((res) => {
                console.log(res)
                if (res.data.errcode == 0) {
                    store.dispatch('userPoint',res.data.data.available)
                }
            })
        }
      })
  }

 

此外,路由带参数跳转,在页面组件keep-alive情况下,也可使用  beforeRouteEnter 带参数跳转,在参数对象to中获取。

你可能感兴趣的:(vue)