I'm diving into the world of Vuex, exploring how to create an auth module. I came across some examples that I'm trying to implement, but I've hit a roadblock when attempting to use axios in my store. My store is structured with separate files for index, actions, getters, etc.
The login
action works fine when it's placed in the actions section of store/index.js
. However, when I moved it to store/actions.js
, I encountered an error stating that axios
is undefined.
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)
})
})
}
}