vue-asyncable
Async data loading plugin for Vue.js
Install
npm install vue-asyncable --save-dev
Usage
import { Asyncable } from 'vue-asyncable'
Then, in your component options, provide an asyncData
function:
Vue.component('example', {
mixins: ['Asyncable'],
data () {
return {
orders: [],
news: []
}
},
asyncData () {
return {
orders: this.$axios.$get('api/orders'),
news: this.$axios.$get('api/news')
}
}
})
Object
Property asyncData can be simple object. In this case you don't need to define initial data elements, the module will set it's automatically
Vue.component('example', {
asyncData: {
orders: axios.$get('api/orders', { user_id: profile.id }),
news: axios.$get('api/news', { user_id: profile.id })
}
})
Promise
You can also return a promise that resolves to the data, and return object with promises and siple types
Vue.component('example', {
async asyncData () {
let profile = await this.$axios.$get('api/profile')
return {
profile,
orders: this.$axios.$get('api/orders', { user_id: profile.id }),
news: this.$axios.$get('api/news', { user_id: profile.id })
}
}
})
Loading State
Your component automatically gets a $loadingAsyncData
meta property, which allows you to display a loading state before the data is loaded:
<div v-if="$loadingAsyncData">Loading...</div>
<div v-if="!$loadingAsyncData">Loaded. Put your real content here.</div>
License
MIT