如何获取this.$store.dispatch的返回值

2023-01-10 11:37:40

目录获取this.$store.dispatch的返回值Action调用根据vuex的this.$store.dispatch()返回值处理逻辑App.vuevuex/store/action.js总...

目录
获取this.$store.dispatch的返回值
Action
调用
根据vuex的this.$store.dispatch()返回值处理逻辑
App.vue
vuex/store/action.js
总结

获取this.$store.dispatch的返回值

this.$store.dispatch() 是用来传值给vuex的mutation改变state。

我们来看看怎么获取this.$store.dispatch() 调用的返回值。

Action

首先看看定义的Action:

 login({ commit }, userInfo) {
  // const { username, password } = usepythonrInfo
  return new Promise((resolve, reject) => {
   login(userInfo).then(response => {
    const { data } = response
    commit('SET_TOKEN', data.token)
    setToken(data.token)
    resolve(response)
   }).catch(error => {
    reject(error)
   })
  })
 },

两个关键点:

返回一个new Promise
return new Promise((resolve, reject)
resolve函数中传入返回值
resolve(response)

调用

      this.$store.dispatch('user/login', this.loginForm)
       .then(res => {
        console.log(res)
        fullLoading.close();
        //登陆首页还是之前访问需要重定向的地址
        this.$router.push({
         path: this.redirect || '/'
        })
        this.loading = false

       })
       .catch(error => {}

在调用里就可以直接通过 res 来直接获取返回值了。

       .then(res => {
        console.log(res)

根据vuex的this.$store.dispatch()返回值处理逻辑

App.vue

    const ret = await this.$store.dispatch('userLogin', {
     username: this.curUserName,
     password: this.curPassword
    })
    if (ret && ret.info) {
     this.$message.success(ret.info)
     await this.$store.dispatch('controlLoginDialog', false)
    } else {
     this.$message.warning(ret)
    }

vuex/store/action.js

 async userLogin ({commit}, account) {
  let userInfo = {}
  return new Promise((resolve, reject) => {
   requestUserLogin(account).then(response => {
    if (response.status === 200) {
     if (response.data.data) {
      userInfo = response.data.data
      userInfo.userName = userInfo.name
      userInfo.isLogin = true
      resolve({
       info: userInfo.userName + ' 登录成功,欢迎进入百度云智学院实验平台'
      })
     } else if (response.data.fail) {
      userInfo.userName = ''
      userInfo.isLogin = false
      myConsole('response.data.fail')
      resolve(response.data.fail)
     }
    } else {
     userInfo.userName = ''
     userInfo.isLogin = false
    }

    commit(USER_LOGIN, {userInfo})
   }).catch(err => {
    myConsole(err)
    reject(err)
   })
  })
 },

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。