我将开始使用Vuex冒险,并制作一些身份验证模块。找到了一些我想遵循的示例,但是在商店中尝试使用axios时遇到了麻烦。我的商店有分开的索引,操作,获取器等文件。
动作login
在store/index.js
中的动作中起作用,但是当我将其放入store/actions.js
文件中时,它表示axios
是未定义的。
store / index.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
// import example from './module-example'
Vue.use(Vuex)
/*
* If not building with SSR mode,you can
* directly export the Store instantiation
*/
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'
export default function(/* { ssrContext } */) {
const Store = new Vuex.Store({
modules: {
// example
},namespaced: false,getters,mutations,actions,state,// enable strict mode (adds overhead!)
// for dev mode only
strict: process.env.DEV,})
return Store
}
store / actions.js
export default {
login({ commit },user){
return new Promise((resolve,reject) => {
commit('auth_request')
axios({ url: 'http://localhost:3000/login',data: user,method: 'POST' })
.then(resp => {
const token = resp.data.token
const user = resp.data.user
localStorage.setItem('token',token)
axios.defaults.headers.common['Authorization'] = token
commit('auth_success',token,user)
resolve(resp)
})
.catch(err => {
commit('auth_error')
localStorage.removeItem('token')
reject(err)
})
})
}
}