我正在为VueJS中的Vuex Store找到swich到模块模式的解决方案。因为我使用NuxtJS所以默认存储将处于经典模式。
我遵循这条指令:https://nuxtjs.org/guide/vuex-store#modules-mode但这不起作用。
希望你的家伙帮助我!
〜/商店/ 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: {
...
}
})
错误:
组件中的调度操作时 [vuex] unknown action type: login
:
async login () {
try {
await this.$store.dispatch('login', {
username: this.signupUsername,
password: this.signupPassword
})
this.signupUsername = ''
this.signupPassword = ''
} catch (e) {}
}
我想切换到带有export const store
的模块,以便将const存储导入我项目中的其他js文件。
答案 0 :(得分:1)
由于您使用的是模块化方法,因此您需要添加{ root : true}
来访问根操作,突变,getter等。例如:
$ store.dispatch('login',{username:this.signupUsername,password: this.signupPassword},{root:true})
`