Vuex获取this对象及深度state监测

Vuex中无法获取到this对象,需要通过dispatch传入上下文this

Vue监测state对象内部字段更新或数组某一数据更新可用:deep: true

computed: mapState({
  user_update_watcher: state => state.account.user_update
}),
watch: {
  user_update_watcher: {
    handler: 'userUpdateWatcher',
    deep: true
  }
},
methods: {
  userUpdate () {
    var params = {}
    params.localMsg = {'msg_server_busy': '系统繁忙,请稍后再试!'}
    this.$store.dispatch('userUpdate', {'context': this, 'userId': this.userId, 'params': params})
  },
  userUpdateWatcher (data, oldData) {
    ...
  }
}
export default {
  state: {
    user_update: {
      'data': null,
      'success': false,
      'timestamp': 0
    }
  },
  mutations: {
    COMMON_USER_UPDATE_CALLBACK: (state, response) => {
      Vue.set(state.user_update, 'timestamp', new Date().getTime())
      let context = response.context
      let httpCode = response.httpCode
      if (httpCode === 403) {
        Vue.set(state.user_update, 'success', false)
        context.$router.push({path: '/login?page=user_update'})
        return
      }
      if (httpCode !== 200) {
        Vue.set(state.user_update, 'success', false)
        context.$dialog.alert({mes: response.localMsg.msg_server_busy, btn_mes: '确认'})
        return
      }
      let code = response.data.code
      if (code !== 0) {
        Vue.set(state.user_update, 'data', null)
        Vue.set(state.user_update, 'success', false)
        context.$dialog.alert({mes: response.data.error.errMsg, btn_mes: '确认'})
        return
      }
      Vue.set(state.user_update, 'data', response.data.data)
      Vue.set(state.user_update, 'success', true)
    }
  },
  actions: {
    userUpdate ({ commit }, object) {
      // 更新用户信息
      api.user_update(object.userId, object.params).then((response) => {
        commit(types.COMMON_USER_UPDATE_CALLBACK, {'context': object.context, 'httpCode': response.status, 'data': response.data})
      }).catch((response) => {
        commit(types.COMMON_USER_UPDATE_CALLBACK, {'context': object.context, 'httpCode': response.status, 'data': response.data, 'localMsg': object.params.localMsg})
      })
    }
  }
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/12/vuex-obtains-this-object-and-deep-state-monitoring/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Vuex获取this对象及深度state监测
Vuex中无法获取到this对象,需要通过dispatch传入上下文this Vue监测state对象内部字段更新或数组某一数据更新可用:deep: true computed: mapState({ user……
<<上一篇
下一篇>>
文章目录
关闭
目 录