Hi I'm a newbie user of Nuxt JS. I'm trying to use Vuex module mode for my Nuxt project.
Basically I'm using axios inside my VueX module. My code below:
store/modules/users.js
import axios from 'axios';
const state = () => ({
users: []
});
// Sets the values of data in states
const mutations = {
setUsers(state, users) {
state.users = users;
}
};
const actions = {
nuxtServerInit(vuexContext, context) {
return axios.get('https://sample-url.com/users')
.then((response) => {
vuexContext.commit('setUsers', response.data.data.results);
})
.catch((err) => {
context.error(err);
});
},
setUsers(vuexContext, users) {
vuexContext.commit('setUsers', users);
}
};
// retrieves the data from the state
const getters = {
getUsers(state) {
return state.users;
}
};
export default {
state,
mutations,
actions,
getters
};
then I include this module in store/index.js
import Vuex from 'vuex';
import Users from "~/store/modules/users";
const createStore = () => {
return new Vuex.Store({
state: {},
mutations: {},
modules: {
Users
}
})
}
export default createStore;
then I get the users stored in my Vuex in one of my pages like: pages/index.vue
<script>
export default {
computed: {
loadedUsers() {
return this.$store.getters.getUsers;
}
}
}
</script>
My questions are:
- I realised whenever I refreshed the page on other pages that I don't need the users, it sends GET request again to my api to fetch users. How can I only use the modules for only pages I need it like pages/index.vue
- How can I use modules to use if for other requests like GET comments should it be under store/modules/comments.js then include it again it store.js