Init Vuex with async data before router starts
by darkylmnx
HTML
<script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue-router.js"></script>
<div id="app" v-cloak></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
#app > div {
background: pink;
padding: 10px;
margin: 10px;
}
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
}
}
})
const router = new VueRouter({
routes: [
{
name: 'home',
path: '/',
component: {
template: `<div>Home, <router-link :to="{name: 'users'}"> click here </router-link> </div>`
}
},
{
name: 'users',
path: '/users',
component: {
template: `
<div>
<p v-for="user in users">
{{ user.name.first }}
</p>
</div>
`,
computed: Vuex.mapState(['users'])
}
}
]
})
router.beforeEach((to, from, next) => {
console.log('beforeEach')
next()
})
const App = {
data() {
return {
ready: false
}
},
template: `
<div id="app">
<h1>Welcome on my community</h1>
<div v-if="ready">
<h2> you cannot see me if ajax not finished</h2>
<router-view></router-view>
</div>
</div>
`,
created() {
// init ajax first
Api.getUsers()
.then(data => store.commit('SET_USERS', data.results)) // commit ou dispatch to store
.then(() => {
console.log('ajax call')
this.ready = true
/* this.$router. */
}) // init ready
}
}
new Vue({
el: "#app",
store,
router,
render(h) {
return h(App)
}
})