0👍
I’ve made this example on how to set the state from external service using axios
// main.js
import Vue from "vue";
import App from "./App.vue";
import Vuex from "vuex";
import axios from "axios";
Vue.config.productionTip = false;
Vue.use(Vuex);
const store = new Vuex.Store({
// create the state to store the data
state: {
todo: {}
},
// make an asynchronous call to get the data
actions: {
getTodoItem(state, index) {
return axios.get(`https://jsonplaceholder.typicode.com/todos/${index}`);
}
},
// set data in state
mutations: {
setTodo(state, value) {
Vue.set(state, "todo", value);
}
}
});
new Vue({
store, // loads the store
render: h => h(App)
}).$mount("#app");
<!-- App.vue -->
<script>
import { mapState, mapActions, mapMutations } from "vuex";
export default {
computed: {
...mapState(["todo"]),
hasTodo() {
return Object.keys(this.todo).length;
}
},
methods: {
...mapActions(["getTodoItem"]),
...mapMutations(["setTodo"]),
async getTodo() {
// random number between 1 and 200
const index = Math.floor(Math.random() * 200) + 1;
const { data } = await this.getTodoItem(index);
this.setTodo(data);
}
},
mounted() {
this.getTodo();
}
};
</script>
<template>
<div id="app">
<div v-if="hasTodo">Todo: {{ todo.title }}</div>
<b v-else>Loading..</b>
</div>
</template>
- [Vuejs]-Upload image using vue js with form text fields
- [Vuejs]-VueJS component prop only shows last JSON entry when reused
Source:stackexchange.com