Created
March 31, 2018 19:04
-
-
Save bskimball/5e9c5d155f591a01583eee9e89e187b3 to your computer and use it in GitHub Desktop.
Simple Vue Data Provider component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div class="provider"> | |
<slot :result="result" :add="add" :remove="remove" :update="update"></slot> | |
</div> | |
</template> | |
<script> | |
import axios from 'axios' | |
import _ from 'lodash' | |
export default { | |
name: 'app-data-provider', | |
props: { | |
url: { | |
type: String, | |
required: true | |
} | |
params: { | |
type: Object, | |
default () { | |
return {}; | |
} | |
} | |
}, | |
data () { | |
return { | |
loading: false, | |
error: false, | |
result: '' | |
}; | |
}, | |
computed: { | |
noResult () { | |
if (!this.error && !this.loading) { | |
return (this.results === ''); | |
} | |
} | |
}, | |
methods: { | |
getData () { | |
this.loading = true; | |
return new Promise((resolve, reject) => { | |
axios.get(this.url, {params: this.params}) | |
.then((response) => { | |
resolve(response.data); | |
}) | |
.catch((error) => { | |
this.error = true; | |
reject(error); | |
}) | |
.then(() => { | |
this.loading = false; | |
}); | |
}); | |
}, | |
add (payload) { | |
if ('data' in this.result) { | |
this.result.data.push(payload); | |
} else { | |
this.result.push(payload); | |
} | |
}, | |
remove (payload) { | |
if ('data' in this.result) { | |
let index = _.findIndex(this.result.data, (item) => { return item.id === payload.id; }); | |
this.result.data.splice(index, 1); | |
} else { | |
let index = _.findIndex(this.result, (item) => { return item.id === payload.id; }); | |
this.result.splice(index, 1); | |
} | |
}, | |
update (payload) { | |
if (this.result.constructor === Array) { | |
let index = _.findIndex(this.result, (item) => { return item.id === payload.id; }); | |
this.result.splice(index, 1, payload); | |
} else { | |
if ('data' in this.result) { | |
let index = _.findIndex(this.result.data, (item) => { return item.id === payload.id; }); | |
this.result.data.splice(index, 1, payload); | |
} else { | |
_.assign(this.result, payload); | |
} | |
} | |
}, | |
reload () { | |
this.getData().then((result) => this.result = result); | |
} | |
}, | |
mounted () { | |
this.getData().then((result) => this.result = result); | |
}, | |
watch: { | |
'params' () { | |
this.getData().then((result) => this.result = result); | |
} | |
} | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment