Tips for verifying the rendered view post data retrieval from an API in Vue JS

Having trouble retrieving data from the API using Vue JS and printing the page? After fetching the data, some elements may not render completely when trying to print, resulting in blank data being displayed. While using a setTimeout function may work for some clients, it is not a perfect solution as it may require setting a longer waiting timeout to ensure all clients can print successfully. This workaround is not ideal.

methods: {
            getData() {
                axios.get('/api/sale/receipt/' + this.$route.params.uuid).then((res) => {
                    this.sale = res.data
                    if(this.sale.customer == null) {
                        this.sale.customer = {}
                    }
                    
                    $('.main-loader').hide();
                    // setTimeout(function() {
                        window.print();
                        window.close();
                    // }, 2000);
                }).catch((res) => {

                });
            }
        },

After the elements have rendered, the print option will pop up. Thank you!

Answer №1

Below is an illustration of how to utilize $nextTick() within Vue.

If you make use of window.print() directly, minus employing $nextTick(), then your printout won't include the list of posts since it requires time to update the DOM.

const { createApp, ref } = Vue 

const App = {
  data() {
    return { 
      posts: [] 
    }
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
          fetch('https://jsonplaceholder.typicode.com/posts')
              .then((response) => response.json())
              .then((data) => 
              {
                this.posts = data;
                this.$nextTick(() => {
                  window.print();
                });
              });
      }   
  }  
}

const app = createApp(App)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
<div v-for="post in posts" :key="post.id">
  <label>Id:</label>{{post.id}}<br/>
  <label>Title:</label>{{post.title}}<br/>
  <label>Body:</label>{{post.body}}<br/>
  <hr/>
</div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

Answer №2

I have finally found the solution to my question.

methods: {
            async getData() {
                await axios.get('/api/sale/receipt/' + this.$route.params.uuid).then((res) => {
                    this.sale = res.data
                    if(this.sale.customer == null) {
                        this.sale.customer = {}
                    }
                    $('.main-loader').hide();
                    // setTimeout(function() {
                        // window.print();
                        // window.close();
                    // }, 2000);
                }).catch((res) => {

                });
                
                window.print();
                window.close();
            }
        },

By adding async getData() to my function and using await with axios, I was able to move the window.print() outside of the axios and now everything is working perfectly.

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

Incorporating vue.js into Shopify's liquid templates for enhanced functionality

I've been trying to figure out how to use Vue template tags within a liquid file, but haven't had any luck finding a solution. The issue arises because both Vue and liquid use the same curly brackets, causing rendering problems for my view data: ...

How to access a custom filter in ng-repeat using AngularJS

I'm working on creating a filter to sort through the items displayed in a table. Specifically, I want to filter out items based on a certain property value that may change depending on user input. I have attempted the following approach and it seems t ...

Revamping the login interface for enhanced user

Whenever I attempt to login by clicking the login button, there seems to be an issue as it does not redirect me to any other page. Instead, I am left on the same page where I initially clicked the button. The intended behavior is for users to be redirected ...

convert a screenplay to javascript

I have a script that can be used to calculate the distance between 2 coordinates. The code is a combination of PHP and JavaScript. I am interested in moving it into a standalone JavaScript file but not sure how to proceed. Below is the script related to & ...

Troubleshooting in Electron: What is the best way to access objects within the render scope from the console?

During my experience in web development, I have always appreciated the ability to access and manipulate variables and functions through the browser's development console at runtime. For instance, if I define a var foo = 3; in my code, I am able to ...

What is the best way to handle multiple axios calls with pagination in a React application?

Discussing React Pagination and Handling Multiple Axios Calls In my current project, I am faced with the challenge of mapping through an array of numbers and making sequential API calls for each one. The API I'm working with returns paginated results ...

How can you determine the index of a table column in JavaScript when you only know its class name?

I am looking for a way to dynamically hide/show table columns based on their classes, without having to add classes to each individual <td> element. This should be accomplished using classes on the columns themselves. Here is a sample of the table ...

Receiving the error "Potential null object. TS2531" while working with a form input field

I am currently working on developing a straightforward form to collect email and password details from new users signing up on Firebase. I am utilizing React with Typescript, and encountering an error labeled "Object is possibly 'null'. TS2531" s ...

Tips for utilizing the setInterval function in javascript to update the background color of the body

Currently, I am tackling a project for my course and I am seeking to modify the body's background color on my website randomly by leveraging the setInterval technique in my JavaScript file. Any suggestions on how to achieve this task? ...

Passport JS fails to pass req.user data to Angular Controller

Currently, I am in the process of developing an application that utilizes an Express/Node backend along with Angular JS for the front end. This stack is fairly new to me, and I have been struggling with retrieving data in an Angular Service + Controller. ...

What could be the reason for my reset function not halting?

Why does my reset button keep clearing the canvas and emptying the chat box even though the return statement is supposed to end the function? Main.js var reset = function() { context.clearRect(0,0, canvas[0].width, canvas[0].height); context.be ...

How to perfectly position an image within a fixed full screen container

When you click on a thumbnail image, a full-screen overlay with a larger version of the image will be triggered using JavaScript. To ensure that the image is centered and resized inside the black overlay when the browser window size changes, I attempted t ...

Determining the most appropriate time to utilize the 'async' built-in function in ES2017 versus implementing 'npm i async' can depend on a variety of factors such

I recently discovered that async/await is a feature of ES2017, however, in some of my previous projects I had to use the package async to implement async/await functionality. Is there a simple way to determine when async can be used without importing it? ...

What is the best way to disable a checkbox option after just one checkbox has been selected?

Issue: I am facing a problem with 2 checkboxes, option A and option B. It is required that at least one of them should be checked. If one checkbox is unchecked, the other should be disabled. However, if both checkboxes are checked, they should remain ena ...

The Correct Way to Implement Google ReCaptcha

I've developed a PHP contact form that performs validation using AJAX/JSON on the server side. The errors are then passed to Javascript for display and adjustments to the HTML/CSS. My challenge now is to integrate Google ReCaptcha with AJAX validatio ...

Sort through the API's array

Currently, I am working with the OpenWeather API's 5-day 3-hour forecast feature and encountering an issue regarding the response JSON. The array contains 40 items, each with a "dt_txt" value in the format of "2018-11-22 15:00:00". My goal is to displ ...

Guide on how to iterate through the list of users within the component

Hello, I'm fairly new to working with react and I've encountered a challenge regarding implementing a loop within this component to display a list of all users. Despite trying numerous approaches, I haven't been able to figure it out. colum ...

Leverage the power of jQuery datetime picker in an ASP.NET content page with a repeater control

Can anyone help me with adding a javascript tag to a content page of my asp.net application? The script is working fine with html tags, but it's not functioning properly within the content. Here is the code snippet that displays a datetime picker: &l ...

Tips on creating Twitter Bootstrap tooltips with multiple lines:

I have been using the function below to generate text for Bootstrap's tooltip plugin. Why is it that multiline tooltips only work with <br> and not \n? I would prefer to avoid having any HTML in my links' title attributes. Current Sol ...

There is an issue with transmitting data from an HTML page to the server and then retrieving data from the server

Upon running this code, I encountered an issue with sending and receiving data. I kindly request assistance in correcting my code. Highlighted below is the server-side code var http = require("http") ; var fs = require("fs") ; http.createServer(function( ...