Init Vue Store with async data
HTML
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>
<div id="app" v-cloak>
<h1>Welcome on my community</h1>
<p v-for="user in users">
{{ user.name.first }}
</p>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
[v-cloak] {
display: none;
}
Vue
const Api = {
getUsers(page = 1) {
return fetch(`https://randomuser.me/api/?page=${page}&results=10&seed=abc`)
.then(resp => resp.json())
}
}
const store = new Vuex.Store({
state: {
users: []
},
mutations: {
SET_USERS(state, payload) {
state.users = payload
}
}
})
// init ajax first
Api.getUsers()
.then(data => store.commit('SET_USERS', data.results)) // commit ou dispatch to store
.then(initVue) // init vue afterwards
function initVue() {
return new Vue({
el: "#app",
store,
computed: Vuex.mapState(['users'])
})
}