Luca
Posted on August 12, 2020
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!
🙋♂️
💖 💪 🙅 🚩
Luca
Posted on August 12, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.