Recently I started to practice Vue, and can't figure out how to organize a "global storage".
And now, to the point:
It is necessary to get user data once (from the server) in order to then work with them from any component.
For example, I need to get data in the components: left menu, top menu and page - these are already three requests, but I would like to limit myself to one :)
I tried vuex, but when used store in components, it makes another one request to the server:
userModule.js
import axios from 'axios';
export const userModule = {
state: () => ({
current: {},
}),
getters: {
getUser(state) { return state.current },
},
mutations: {
setUser(state, user) { state.current = user },
},
actions: {
async updateUser({state, commit}) {
try {
const response = await axios.get('/office/api/me');
commit('setUser', response.data);
} catch (e) {
console.log(e);
alert('Error');
}
},
},
namespaced: true,
}
The code I use in components:
import {mapState} from 'vuex';
export default {
created() {
this.$store.dispatch("user/updateUser");
},
computed: {
...mapState({
user: state => state.user.current,
}),
}
}
CodePudding user response:
Only use updateUser
once
The error here is that every component will load the user, since every created()
looks like:
created() {
this.$store.dispatch("user/updateUser");
}
You should initialize VueX just one time. Depends how your Vue3 project is set up.
You should have an App.vue
where you can put your call in create()
, but only there. Then $store
should be available from other components with the user data, as soon as the user is loaded.