我正在尝试获取此信息并将其放入“用户”中:
VueJS中的操作:
export default new Vuex.Store({
state: {
status: '',
token: localStorage.getItem('token') || '',
user : {},
test : []
},
mutations: {
auth_request(state){
state.status = 'loading'
},
auth_success(state, token, user){
state.status = 'success'
state.token = token
state.user = user
},
auth_error(state){
state.status = 'error'
},
logout(state){
state.status = ''
state.token = ''
},
},
actions: {
login({commit}, user){
return new Promise((resolve, reject) => {
commit('auth_request')
axios.get('http://localhost:8080/offreeduwar/api/Useraccount/login/'+ user.email+'/'+user.password)
.then((resp) => {
const token = resp.data.token
const user = resp.data
console.log(test)
localStorage.setItem('token', token)
// Add the following line:
axios.defaults.headers.common['Authorization'] = token
commit('auth_success', token, user)
resolve(resp)
})
.catch(err => {
commit('auth_error')
localStorage.removeItem('token')
reject(err)
})
})
},
但是在Vue devtool中,始终都是:用户状态为空,因此问题在于如何将该信息提供给用户以使用此变量
答案 0 :(得分:1)
存储中的commit方法具有两个参数:突变的名称和参数(如果它是原始类型,则值本身,如果是对象,则为对象)。所以你应该这样尝试:
commit('auth_success', { token, user })
然后:
auth_success(state, payload){
state.status = 'success'
state.token = payload.token
state.user = payload.user
},