Generate and save a document

Upon clicking the button, I am trying to generate a CSV file and download it right away. My current approach is as follows:

html:

<a class="btn btn-primary" @click="downloadCsv">Download CSV</a>
  <a v-if="fileObjectUrl !== null" ref="downloadCsv" :download="fileName" 
     :href="fileObjectUrl"
     :downloadUrl="downloadurl"></a>

JavaScript:

downloadCsv () {
  let csv = this.createCsv()
  let blob = new Blob([csv], { type: 'text/csv' })
  this.fileObjectUrl = window.URL.createObjectURL(blob)
  this.$refs.downloadCsv.click()
},

However, this method does not work smoothly as Vue updates the fileObjectUrl with a delay, which causes the file to be downloaded only after clicking the button twice. Is there an alternative way to generate and download the file in sequence?

Answer №1

Referencing Vue's Async Update Queue:

If you haven't already realized, Vue executes DOM updates asynchronously. When a data change is detected, it creates a queue and stores all the data changes that occur within the same event loop. If a watcher is triggered multiple times, it will be added to the queue only once. This mechanism of buffering and de-duplication helps in minimizing unnecessary computations and manipulations of the DOM. Subsequently, in the next event loop cycle, Vue processes the queue and carries out the necessary work.

At the point when you trigger the click(), Vue may not have updated the DOM yet, so you need to ensure that Vue waits for the next tick. To achieve this, schedule the click() action after the next tick using Vue.$nextTick().

Therefore, in your case, the solution would involve:

this.$nextTick(function(){
    this.$refs.downloadCsv.click();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for setting dynamic variables as CSS content within Vue.js?

Forgive my lack of expertise, but I am interested in learning more about utilizing dynamic variables and CSS within Vue. I have a concept in mind where pressing a button would result in the letters of the button label spacing out further. Is it feasible t ...

Queue with promises

My challenge is to process an array of files, in batches of N. I have a function called doWork that returns promises. var files = [] var doWork = function(file) { return asyncFn(file) } I want the ability to dynamically add items to this queue. Updat ...

Is there a way I can retrieve a cookie stored in an Express middleware even if the req.cookies object is returning empty?

I am currently working on validating a cookie using the cookie-parser module to verify if the user is authenticated to access restricted routes within my application. My technology stack includes NodeJS and Express for the server, and Sveltekit for the fro ...

Implement a hover animation for the "sign up" button using React

How can I add an on hover animation to the "sign up" button? I've been looking everywhere for a solution but haven't found anything yet. <div onClick={() => toggleRegister("login")}>Sign In</div> ...

Tips for connecting 2 Bootstrap 5 carousels

I currently have 2 Bootstrap 5 carousels (carousel-a & carousel-b) on the same page and I want them to be synchronized with each other. I believe this can be achieved using JavaScript, but I am not very familiar with it. Below is the structure of carousel- ...

Accessing a local JSON data file via an AJAX call

function fetchColor() { var promise = $.Deferred(); $.ajax ({ url: 'ajax/color/Red.json', dataType: 'json', type: 'get', success: function(data){ promise.resolve(data); ...

Encountering an issue with npm start when attempting to launch the local host server for a React.js project

Encountering an issue with npm start Error message: 'Equipment' is not recognized as a command, operable program or batch file. internal/modules/cjs/loader.js:983 throw err; ^ Error: Module not found 'C:\Users\Home\Deskto ...

ReactiveJS - Adding elements to an array and encountering the error of undefined

In two separate JavaScript files, I have 2 arrays declared as shown below: Index.JS: const [product, setProduct] = useState([]); const [item] = useState([ { name: 'Blue Dress', Image: '/static/media/Dress.1c414114.png', Pr ...

Is there an equivalent of HtmlSpecialChars in JavaScript?

It seems that finding this is proving more difficult than anticipated, even though it's such a simple concept... Is there an equivalent function in JavaScript to PHP's htmlspecialchars? While it's possible to create your own implementation, ...

arrange data within an angular ng-repeat

I'm facing a bit of a challenge with Angular since I'm still new to it. My data looks like this: $scope.datas =[ {name:'haha',datetime:'2015-06-06 09:24:34'}, {name:'taha',datetime:'2015-07-06 19:10:45& ...

Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name Below is my concept along with some sample code for reference: $(".clickCompare").click(function ({ var id = $(this).attr('data-id'); var ...

How can I add scrolling functionality to the active list item with React?

I created a music player that allows users to search for songs by artist. Check out the CODE SANDBOX here! Take a look at how the SongsList component is structured in my project: const SongsList = (props) => { const { loading, errorMess ...

Transitioning between javascript functions

Having some issues with a switch case statement, also tried using if-else but no luck. In the HTML code: <select onBlur="functionCalc()" id="art"> <option value="hours" id="hours">Hours</option> <option value="minutes" id="mins">M ...

When using React.js with Leaflet, ensure that the useEffect hook is only run on Mount when in the

I have encountered an issue where I need to ensure that the useEffect Hook in React runs only once. This is mainly because I am initializing a leaflet.js map that should not be initialized more than once. However, anytime I make changes to the component&a ...

Execute JavaScript function after the reset button has been clicked

Is there a way to execute a function right after the form elements are reset by the <input type="reset"/> button? ...

Utilize JavaScript to implement CSS using an "if" statement

I am currently working on implementing iOS web app properties into my website. My goal is to create a <div> at the top of the page and apply specific CSS styles when a certain condition is met in a JavaScript script. Unfortunately, I am facing issue ...

The Material-UI Snackbar stubbornly refuses to disappear even after setting its controlled state to false

I am currently working with a Snackbar component that relies on the redux state for control. I have implemented the onRequestClose() function in an attempt to disable the clickaway close feature. However, I have encountered an issue where setting the prop ...

How can I modify a dynamically generated table to include rowspan and colspan attributes in the rows?

My table was automatically created using data from the database. var rows = ""; rows += "<tr class='row_primary'>"; rows += "<td>COL 1</td>"; rows += "<td>COL 2</td>"; rows += "<td> ...

The face textures are not being applied correctly to the model imported in THREE.js

I'm having trouble importing a model exported from blender using the THREEJS exporter. The model loads correctly in my scene with the materials applied, such as the car appearing yellow and the glass being transparent as intended. However, I am facin ...

Encountering a Peer dependency problem while executing node within a docker environment

Currently, I am utilizing `node-pg-migrate`, which has a peer dependency on `pg`. Here is an excerpt from the library's `package.json` file: "peerDependencies": { "pg": "^4.3.0" }, My attempt to execute the application in Docker involves the fo ...