I'm finding solution to swich to module mode for Vuex Store in VueJS. Because I use NuxtJS so the default store will be in classic mode.
I follow this instruction: https://nuxtjs.org/guide/vuex-store#modules-mode but It's not work.
Hope your guy helps me!
~/store/index.js
export const AuthenticationStore = new Vuex.Store({
state: {
authUser: null,
userInfo: null,
token: null
},
mutations: {
SET_USER: function (state, user) {
state.authUser = user
},
SET_TOKEN: function (state, token) {
state.token = token
instance.defaults.headers = { Authorization: 'Bearer ' + token }
}
},
actions: {
async nuxtServerInit ({ commit }, { req }) {
try {
const jwtCookie = req.headers.cookie.split(';').find(c => c.trim().startsWith('token='))
if (jwtCookie) {
let token = jwtCookie.split('=')[1]
let payload = jwtDecode(token)
let date = Date.now() / 1000
if (payload.exp > date) {
commit('SET_USER', payload)
commit('SET_TOKEN', token)
instance.defaults.baseURL = backendURL
}
}
} catch (error) {
console.log('nuxtServerInit Failed')
}
},
async login ({ commit }, { username, password }) {
try {
const { data } = await axios.post('http://localhost:8000/api/v1/api-token-auth/login', {
username,
password
})
let payload = jwtDecode(data.token)
Cookie.set('token', data.token, {
expires: null
})
commit('SET_TOKEN', data.token)
commit('SET_USER', payload)
} catch (error) {}
},
async logout ({ commit }) {
Cookie.remove('token')
commit('SET_USER', null)
commit('SET_TOKEN', null)
window.location.href = '/'
}
},
modules: {
...
}
})
Error:
[vuex] unknown action type: login
when dispatch action in components:
async login () {
try {
await this.$store.dispatch('login', {
username: this.signupUsername,
password: this.signupPassword
})
this.signupUsername = ''
this.signupPassword = ''
} catch (e) {}
}
I want to switch to modules with write export const store
in order to import const store into other js file in my project.