Skip to content

Instantly share code, notes, and snippets.

@lucascaires
Last active December 21, 2017 21:41
Show Gist options
  • Save lucascaires/5b10bda8172d06f1dc4e0778344d6802 to your computer and use it in GitHub Desktop.
Save lucascaires/5b10bda8172d06f1dc4e0778344d6802 to your computer and use it in GitHub Desktop.
<template>
<button @click="download"><slot></slot></button>
</template>
<script>
export default {
props: ['data', 'filename', 'separator'],
computed: {
sep() {
return this.separator || ','
}
},
methods: {
download() {
console.log(this.data)
let data = this.parse(this.data)
let a = document.createElement('a')
a.href = 'data:text/csv;charset=UTF-8,' + '\uFEFF' + encodeURIComponent(data)
a.download = this.filename
document.body.appendChild(a)
a.click();
},
parse: function (data) {
let csv = ''
//Adding header
for(let key in data[0]) {
csv += key + this.sep
}
csv += '\r\n'
//Adding body
data.map(item => {
for (let key in item) {
csv += item[key] + this.sep
}
csv = csv.slice(0, csv.length - 1)
csv += '\r\n'
})
return csv
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment