Hi Dev Friends! 🤠
In this.tutorial i will show you in which mode you can use Axios with Vuex, and call it on you file.Vue.
STEP ONE:
First of all you can add Vuex on your project:
0️⃣) I suggest you to add this, during the installation of Vue.cli, via "manual installation":
vue create project
After this you need to install Axios:
npm install --save axios vue-axios
Import Axios on your store -> index.js
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex)
Vue.use(VueAxios, axios)
STEP TWO:
And now let's create👩💻:
1️⃣)Determinate your items.
export default new Vuex.Store({
state: {
items: [],
},
2️⃣)Your getter:
getters: {
items: state => {
return state.items;
}
},
3️⃣)Mutation of your items
mutations: {
SET_Item (state, items) {
state.items = items
}
},
4️⃣)Action for call your API on you file.Vue
actions: {
loadItems ({ commit }) {
axios
.get('Your API link', {
headers: {
'Ocp-Apim-Subscription-Key': 'your key',
}
})
.then(response => response.data)
.then(items => {
console.log(items);
commit('SET_Items', items)
})
}
},
});
STEP THREE:
Now it's time to call your "items" on your file.Vue:
1️⃣)Import you mapState from vex:
<script>
import { mapState } from 'vuex';
2️⃣) With mounted you can stamp your API, and use "dispatch" method to call the "action" (the difference with mutations is you can use "mounted" method).
mounted () {
this.$store.dispatch('loadItems')
},
3️⃣)Add mapState on your computed:
computed: mapState([
'items'
]),
</script>
4️⃣)Compile you template with your API.
<template>
<div class="my-items">
<div v-for="item in items" :key="items.id">
// Your v-for...
</div>
</div>
</template>
Hope I help you!
🙋♂️
Top comments (4)
U can access to the getter as below:
computed: {
// mix the getters into computed with object spread operator
...mapGetters([
'items',
])
}
Then you can use in your tag:
<div v-for="item in items" :key="items.id">
// Your v-for...
</div>
Is it not possible to import vue-axios in main.js alone as it is suggested in the docs and then be able to use it in actions because in your current approach you don't need vue-axios and can do with just importing axios
Small typo: in mutations should be "SET_Items"
Some comments may only be visible to logged-in visitors. Sign in to view all comments.