To implement a feature to export data to CSV in Vue.js, you can follow these steps:
json2csv
library using npm or yarn. This library will help in converting JSON data to CSV format.bashnpm install json2csv
or
bashyarn add json2csv
javascript<template>
<div>
<button @click="exportToCSV">Export to CSV</button>
</div>
</template>
<script>
import json2csv from 'json2csv';
export default {
data() {
return {
// Your data array
data: [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Doe', age: 40 }
],
// Define fields for CSV header
fields: ['id', 'name', 'age']
};
},
methods: {
exportToCSV() {
const csv = json2csv.parse(this.data, { fields: this.fields });
// Create a Blob and a link element to trigger the download
const blob = new Blob([csv], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'export.csv';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
}
};
</script>
In the template, add a button or any other element that will trigger the exportToCSV method when clicked.
Replace the data
array with your actual data that you want to export.
Define the fields
array which contains the keys of the objects in your data array. This will be used as the header in the CSV file.
When the user clicks the export button, the exportToCSV
method will be called. This method will convert the data array to CSV format using the json2csv library and initiate the download of the CSV file.
That's it! You've implemented a feature to export data to CSV in Vue.js.