I'm experimenting with vuex and I was looking for best way to organize my vuex files I finished with something like this:
/src/store/user/state.js:
export default {
state: {
user: null
}
}
/src/store/user/getters.js:
export default {
getters: {
user (state) {
return state.user
}
}
}
/src/store/user/mutations.js:
export default {
mutations: {
'SET_USER' (state, user) {
state.user = user
}
}
}
/src/store/user/actions.js
export default {
actions: {
loginUser ({ commit }, params) {
commit('SET_USER', {id: 1})
}
}
}
/src/store/user/index.js
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
export default {
state,
getters,
actions,
mutations
}
/src/store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
user
}
})
When I load my code it returns in console following error:
vuex: unknown getter: user
Each of your user-related files are using export default
, which means when you import those files, you are naming the entire object being exported state
, getters
, etc.
So, in the scope of index
, the state
variable has a property named state
, the getters
variable has a property named getters
, etc. And this is throwing things off.
You should export a const
for each of these files instead:
export const state = {
user: null,
}
And then when importing grab the named const
like so:
import { state } from './state'
Alternatively, you could just remove the properties for state
, getters
, etc. from each file:
// state.js
export default {
user: null,
}
And then import like you're doing already:
import state from './state'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With