如何獲取this.$store.dispatch的返回值
更新時間:2023年01月10日 10:54:55 作者:三分惡
這篇文章主要介紹了如何獲取this.$store.dispatch的返回值問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
獲取this.$store.dispatch的返回值
this.$store.dispatch() 是用來傳值給vuex的mutation改變state。
我們來看看怎么獲取this.$store.dispatch() 調(diào)用的返回值。
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) ? ? ? }) ? ? }) ? },
兩個關(guān)鍵點:
- 返回一個new Promise
return new Promise((resolve, reject)
- resolve函數(shù)中傳入返回值
resolve(response)
調(diào)用
? ? ? ? ? ? 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 => {}
在調(diào)用里就可以直接通過 res 來直接獲取返回值了。
? ? ? ? ? ? ? .then(res => { ? ? ? ? ? ? ? ? console.log(res)
根據(jù)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 + ' 登錄成功,歡迎進入百度云智學(xué)院實驗平臺' ? ? ? ? ? ? }) ? ? ? ? ? } 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) ? ? ? }) ? ? }) ? },
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue中的v-model原理,與組件自定義v-model詳解
這篇文章主要介紹了vue中的v-model原理,與組件自定義v-model詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08