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

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

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


Action

首先看看定义的Action:

  login({
    
     commit }, userInfo) {
    
    
    // const { username, password } = userInfo
    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)



参考:

【1】:如何获取vuex的action的返回值(axios请求为例)
【2】:vuex中 this.$store.dispatch() 与 this.$store.commit()方法的区别

猜你喜欢

转载自blog.csdn.net/sinat_40770656/article/details/109996351
今日推荐