|
| 1 | +# vue-async-data |
| 2 | + |
| 3 | +> async data loading plugin for Vue.js |
| 4 | +
|
| 5 | +### Install |
| 6 | + |
| 7 | +``` bash |
| 8 | +npm install vue-async-data |
| 9 | +``` |
| 10 | + |
| 11 | +### Usage |
| 12 | + |
| 13 | +``` js |
| 14 | +var Vue = require('vue') |
| 15 | +var asyncData = require('vue-async-data') |
| 16 | + |
| 17 | +// use globally |
| 18 | +// you can also just use `asyncData.mixin` where needed |
| 19 | +Vue.use(asyncData) |
| 20 | +``` |
| 21 | + |
| 22 | +Then, in your component options, provide an `asyncData` function: |
| 23 | + |
| 24 | +``` js |
| 25 | +Vue.component('example', { |
| 26 | + asyncData: function (resolve, reject) { |
| 27 | + // load data and call resolve(data) |
| 28 | + // or call reject(reason) if something goes wrong |
| 29 | + setTimeout(function () { |
| 30 | + // this will call `vm.$set('msg', 'hi')` for you |
| 31 | + resolve({ |
| 32 | + msg: 'hi' |
| 33 | + }) |
| 34 | + }, 1000) |
| 35 | + } |
| 36 | +}) |
| 37 | +``` |
| 38 | + |
| 39 | +You can also return a promise that resolves to the data to be set: |
| 40 | + |
| 41 | +``` js |
| 42 | +Vue.component('example', { |
| 43 | + asyncData: function () { |
| 44 | + return someServiceThatReturnsPromise.get(12345) |
| 45 | + .then(function (msg) { |
| 46 | + return { |
| 47 | + msg: msg |
| 48 | + } |
| 49 | + }) |
| 50 | + } |
| 51 | +}) |
| 52 | +``` |
| 53 | + |
| 54 | +Parallel fetching with `Promise.all` and ES6: |
| 55 | + |
| 56 | +``` js |
| 57 | +Vue.component('example', { |
| 58 | + asyncData() { |
| 59 | + return Promise.all([ |
| 60 | + serviceA.get(123), |
| 61 | + serviceB.get(234) |
| 62 | + ]).then(([a, b]) => ({a, b})) |
| 63 | + } |
| 64 | +}) |
| 65 | +``` |
| 66 | + |
| 67 | +Your component automatically gets a `$loadingAsyncData` meta property, which allows you to display a loading state before the data is loaded: |
| 68 | + |
| 69 | +``` html |
| 70 | +<div v-if="$loadingAsyncData">Loading...</div> |
| 71 | +<div v-if="!$loadingAsyncData">Loaded. Put your real content here.</div> |
| 72 | +``` |
| 73 | + |
| 74 | +Or, if you prefer to wait until data loaded to display the component, you can use `wait-for` to listen for the `async-data` event, which is automatically emitted when the data is loaded: |
| 75 | + |
| 76 | +``` html |
| 77 | +<example wait-for="async-data"></example> |
| 78 | +``` |
0 commit comments