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

Problem with the show/hide feature on jQuery. Automatically scrolls to the beginning of the page

On my website, I have successfully implemented two basic Show / Hide links that are working great. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" conte ...

Simple Steps for Making a Get Request using Vuex in Vue.js

I'm trying to figure out how to store products in Vuex within my index component. import Vue from 'vue' import Vuex from 'vuex' import cart from "./modules/cart"; import createPersistedState from "vuex-persistedstate ...

The input box fails to show larger values on the user's page

Show me the biggest number that the user enters in an input box and then display it back to them. I need some improvements to my code, ideally making it possible with just one input box instead of two. <!DOCTYPE html> <html la ...

utilize console.log within the <ErrorMessage> element

Typically, this is the way the <ErrorMessage> tag from Formik is utilized: <ErrorMessage name="email" render={(msg) => ( <Text style={styles.errorText}> ...

What is the best way to efficiently import multiple variables from a separate file in Vue.JS?

When working with a Vue.JS application and implementing the Vuex Store, I encountered an issue in my state.js file where I needed to import configurations from another custom file, specifically config.js. Upon running it, I received the following warning ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...

The React DOM element undergoes mounting and unmounting on each render cycle when it should be simply altered/updated

As per the React documentation, callback refs are invoked during both component mounting (with the DOM element's value) and unmounting (with null): When a React component mounts, the ref callback is triggered with the actual DOM element, and when it ...

The functionality of a basic each/while loop in jQuery using CoffeeScript is not producing the desired results

I've been experimenting with different methods to tackle this issue. Essentially, I need to update the content of multiple dropdowns in the same way. I wanted to use an each or a while loop to keep the code DRY, but my experience in coffeeScript is li ...

Having trouble with Vue JS not showing the footer on your website?

I recently set up vue cli and encountered an issue where my navbar component shows up fine, but the footer component does not display properly. When I navigate to other CMS pages, both the navbar and footer appear together without any text displayed in bet ...

Securing Credit Card Numbers with Masked Input in Ionic 3

After testing out 3-4 npm modules, I encountered issues with each one when trying to mask my ion-input for Credit Card numbers into groups of 4. Every module had its own errors that prevented me from achieving the desired masking result. I am looking for ...

Change the price directly without having to click on the text field

Our Magento marketplace site is currently utilizing the code below for updating prices. However, we are looking to make the price field editable without requiring a click on the textfield. This means that users should be able to edit the price directly wi ...

Targeting an HTML form to the top frame

Currently, I have a homepage set up with two frames. (Yes, I am aware it's a frame and not an iFrame, but unfortunately, I cannot make any changes to it at this point, so I am in need of a solution for my question.) <frameset rows="130pt,*" frameb ...

Unexpected quirks noticed in the .html() function with jQuery and JavaScript

I have this straightforward HTML code: <td id="comment_td"> </td>. Notice the two spaces inside the td tags. I am checking the content of the td element like this: if (!$('#comment_td').html()) { $('#comment_td').html( ...

Notifying with Jquery Alert after looping through routes using foreach loop

I am trying to create a jQuery alert message that displays after clicking on a dynamically generated button in the view using a foreach loop. The issue I am facing is that only the first button in the loop triggers the alert, while the subsequent buttons ...

DiscordJS: updating specific segment of JSON object

I am currently working on a Discord bot using discord.JS that involves creating a JSON database with specific values. I'm wondering how I can modify the code to edit a particular object within the JSON instead of completely replacing it. if (message.c ...

Getting a variable from an ajax call and using it in a Pug template

Currently, I am experimenting with Express and Pug to learn some new concepts. Upon making a request to a website, I received some dynamic information stored in an array. However, I am facing challenges when trying to iterate over this array using Pug. The ...

What could be causing the jQuery spritely animation to display an additional frame upon the second mouseenter event?

I have been experimenting with CSS sprites and the jQuery plugin called spritely. My goal is to create a rollover animation using a Super Mario image. When the mouse hovers over the Super Mario <div>, I want the animation to play forward. And when t ...

Error thrown: Upon attempting to reopen the modalbox after closing it, an uncaught TypeError is encountered, indicating that the function $(...).load

An unexpected error occurred: $(...).load(...).modal is not functioning properly After closing a modal, I encountered this error in the console when attempting to reopen it. Strangely, it seems to work intermittently for a few times before throwing this e ...

Navigating through sections in NextJS-14: Utilizing useRef for seamless scrolling

In the past, I had developed an older portfolio website using Vite React + TS and implemented useRef for scrolling to sections from the Navbar. Now, my goal is to transition this portfolio to NextJS 14. I transferred my old components and style folders in ...

Leveraging the power of javascript to include content before and after

I am looking to understand how I can insert an HTML element before and after certain elements. For example, let's say we have the following code in a real file: <ul class="abcd" id="abcd></ul> How can I display it like this using JavaScr ...