Vue AutoFetch
Better and Vue-style data fetching
Installation
$ yarn add vue-autofetch# or $ npm i --save vue-autofetch
Getting Started
Vue // use with in any place of the app
components: AutoFetch // ...
API
Props:
clear
[default:false
] - if true, then set response and error to null if new request has started.data
[required] - request data, passed to handler. If changes, then component automatically downloads new data.handler
[default:fetch
] - function which is called in order to do request. Should return a promise. If resolved, then state is changed tosuccess
and result is passed toresult
variable. If rejected, then state is changed tofailure
and error is passed toerror
variable.threshold
[default:fn => () => fn()
] - function that controls frequency of requests (for example debounce or throttle from lodash). It receives a function [1] which should return a function which calls function [1].
Methods:
refresh
- reload request.
Events:
success
- called when received a successful response. Arguments:response
.failure
- called when request failed. Arguments:error
.start
- called when request has started (state
set to'loading'
). Arguments: empty.done
- called when request is resolved or errored. Arguments:success
(true
orfalse
).
Usage
The component can be used in several ways:
<!-- as a renderless component --> Loading... Success: {{ items.result }} Error: {{ items.error }} Refresh <!-- as a component with default slot --> Loading... Success: {{ result }} Error: {{ error }} Refresh <!-- as a component with slots for different states --> Loading... Success: {{ result }} Error: {{ error }} Refresh
As I stated before, fetch()
is used, but you should override it and even provide some throttling.
You can do this by extending auto-fetch
component or passing some global variable as props: <auto-fetch v-model="items" :data="request" v-bind="$request" />
.
Example of global mixin for this:
Vue
License
Released under the MIT license.