詳解vuex中的this.$store.dispatch方法
vuex中的this.$store.dispatch方法
main.js
new Vue({ el:'#app', router, store, render:h=>h(APP) })
store/index.js
import Vue from 'vue' import Vuex from 'vuex' import app from './modules/app' import user from '.modules/user' import getters from '.getters' import permission from './modules/permission' Vue.use(Vuex) const store=new Vuex.Store({ modules:{ permission, app, user }, getters }) export default store
在store/modules文件夾里的user.js,聲明user并釋放出來。
const user = { state: { token: '', roles: null, isMasterAccount:true, }, mutations: { SET_TOKEN: (state, token) => { state.token ="Bearer " +token }, }, actions: { // 登錄 Login({ commit }, userInfo) { return new Promise((resolve, reject) => { login(userInfo.account, userInfo.password).then(x => { if(x.status==200){ const tokenV = x.data.token.tokenValue commit('SET_TOKEN', tokenV) document.cookie=`AuthInfo=Bearer ${tokenV};path:/`; token="Bearer "+tokenV; //setToken("Bearer " +token) resolve(); } }).catch(error => { console.log("登錄失敗") reject(error) }) }) }, } } export default user
注:必須要用commit(‘SET_TOKEN’, tokenV)
調(diào)用mutations
里的方法,才能在store
存儲(chǔ)成功。
handleLogin() { this.loading = true this.$store.dispatch('Login', this.loginForm).then(() => { this.$router.push({ path: '/manage/merchant/account' }); //登錄成功之后重定向到首頁 this.loading = false // this.$router.push({ path: this.redirect || '/' }) }).catch(() => { this.loading = false }) }
this.$store.dispatch(‘Login’, this.loginForm)
來調(diào)取store
里的user.js的login
方法,從而要更新。
vuex 中dispatch 和 commit 的用法和區(qū)別
dispatch:含有異步操作,例如向后臺(tái)提交數(shù)據(jù),寫法: this.$store.dispatch('action方法名',值)
commit:同步操作,寫法:this.$store.commit('mutations方法名',值)
到此這篇關(guān)于vuex中的this.$store.dispatch方法的文章就介紹到這了,更多相關(guān)vuex中this.$store.dispatch方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue 報(bào)錯(cuò)TypeError: this.$set is not a function 的解決方法
這篇文章主要介紹了Vue 報(bào)錯(cuò)TypeError: this.$set is not a function 的解決方法,分享給大家,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-12-12Vue+Node實(shí)現(xiàn)商品列表的分頁、排序、篩選,添加購物車功能詳解
這篇文章主要介紹了Vue+Node實(shí)現(xiàn)商品列表的分頁、排序、篩選,添加購物車功能,結(jié)合實(shí)例形式分析了vue.js前臺(tái)商品分頁、排序、篩選等功能及后臺(tái)node.js處理技巧,需要的朋友可以參考下2019-12-12vue選項(xiàng)卡Tabs組件實(shí)現(xiàn)示例詳解
這篇文章主要為大家介紹了vue選項(xiàng)卡Tabs組件實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11vue項(xiàng)目實(shí)現(xiàn)國際化的基本思路與詳細(xì)步驟
國際化是指項(xiàng)目能夠根據(jù)不同國家的語言進(jìn)行轉(zhuǎn)換,便于不同國家的用戶使用,這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目實(shí)現(xiàn)國際化的基本思路與詳細(xì)步驟,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-04-04