user.js
const user = {
name: 'user',
state: {
token: getToken(),
},
mutations: {
SET_TOKEN: (state, token) => {
state.token = token
}
},
actions: {
switchLogin({commit}, userInfo) {
return new Promise((resolve, reject) => {
switchAgencySource(userInfo).then(res => {
const token = res.object.token
setToken(token)
commit('SET_TOKEN', token)
resolve(res)
}).catch(error => {
reject(error)
})
})
},
}
}
需要调用的页面,例如index
import {mapActions} from 'vuex'
export default {
data(){
return {}
},
methods:{
...mapActions({
vuexSwitchLogin: 'user/switchLogin'
}),
toggleItemSelect(item){
const param = {
customerNo: row.customerNo,
agencySource:row.agencySource,
dmCustomerNo:row.dmCustomerNo,
phoneNo:row.phoneNo,
token:this.$store.state.user.token
}
this.vuexSwitchLogin(param).then((res) => {
console.log(res)
this.getSuccess()//自己需要的事件
return
}).catch(error => {
uni.showToast({
title: error.message,
icon: 'none'
})
}).finally(e => {})
}
}
}
通过使用mapMutations
辅助函数将该mutation映射到组件的方法中,然后在需要修改token的地方调用setToken(token)、commit('SET_TOKEN', token)
来更新token。