Vue Js Download JSON Data on Click:In Vue.js, you can download JSON data on click by creating a click event handler and using the built-in browser functionality. First, define a method that will be triggered when the download button is clicked. Within this method, create a new Blob object with the JSON data and set its MIME type to “application/json”. Then create a temporary anchor element using the document.createElement() method. Set the anchor’s href attribute to the URL object created from the Blob, and set the download attribute to specify the filename. Finally, trigger a click event on the anchor element using the click() method.
How can I implement a Vue js feature to download JSON data when a button is clicked?
This Vue.js code sets up a button that triggers a download of JSON data when clicked. The data is an array of objects, each representing a person with attributes like name, age, and email.
The code converts the data to a JSON string, creates a Blob object with the JSON data, and generates a URL for it. It then creates a link element, sets the URL and filename, triggers a click on the link, and revokes the URL after the download completes.
This allows the user to download the data as a JSON file named “data.json” on click.
Vue Js Download JSON Data on Click Example
<div id="app">
<button @click="downloadFile">Download</button>
</div>
<script type="module">
const app = new Vue({
el: "#app",
methods: {
downloadFile() {
const data = [
{
name: 'John Doe',
age: 30,
email: 'johndoe@example.com'
},
{
name: 'Jane Smith',
age: 25,
email: 'janesmith@example.com'
},
{
name: 'Alice Johnson',
age: 35,
email: 'alicejohnson@example.com'
},
{
name: 'Bob Williams',
age: 40,
email: 'bobwilliams@example.com'
},
{
name: 'Sarah Davis',
age: 28,
email: 'sarahdavis@example.com'
}
];
const jsonData = JSON.stringify(data);
const blob = new Blob([jsonData], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'data.json';
link.click();
URL.revokeObjectURL(url);
}
}
});
</script>