Reputation: 2754
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:
Upvotes: 1
Views: 3838
Reputation: 3579
When you set up modules in your vuex store they are simply part of your store, which is of course global and always will be. Therefore you can't apply it only to select pages or components. If you want to limit your api call to only those pages that use the returned data you could do that in a couple of ways.
Firstly you can take the api call out of the store altogether and make it in your page using asyncData. So something like this:
//users.vue
<script>
export default {
data: () => ({
users: []
}),
async asyncData({$axios}) {
let {data} = await $axios.$get('https://sample-url.com/users')
return {
users: data
}
}
}
</script>
Otherwise if you'd rather keep your api calls in the store, you can take it out of nuxtServerInit and dispatch it from the page like so.
const actions = {
nuxtServerInit(vuexContext, context) {
},
setUsers(vuexContext, users) {
return axios.get('https://sample-url.com/users')
.then((response) => {
vuexContext.commit('setUsers', response.data.data.results);
})
.catch((err) => {
context.error(err);
});
}
};
then dispatch setUsers from your page like so:
mounted: function () {
this.$nextTick(function () {
this.$store.dispatch('setUsers')
})
},
computed: {
loadedUsers() {
return this.$store.getters.getUsers;
}
}
As for the second part of your question, any other vuex module can be used in the same way.
Upvotes: 1