Vue 2 updates and prints after loading the page

50 Views Asked by At

I use Vue 2.5, I update the data after the created function fetch API returns, and execute window.print() in the updated function.

It still shows blank.

created function

created() {
  axios.get(`/api/pickUp/preview`, {
    params: {
      code,
    },
  }).then((res) => {
    this.preview = true;
    this.shipment = res.data.data.shipments;
    this.selectedShipment = res.data.data.shipments;
    this.price = res.data.data.price;
  });
},

updated function

updated() {
  if(this.preview) {
    this.$nextTick(() => {
      window.print();
    });
  }
},

Print Screen

In fact, the page has information

I tried using setTimeout or executing $nextTick directly at the bottom of the created function.

1

There are 1 best solutions below

5
Huzaifa Shah On

There are some things you can try to make this work. Since there's no working jsFiddle for this problem, I can only suggest you try these.

  • Try converting the created hook into an async function and await the axios call.

    async created() {
        await axios.get(`/api/pickUp/${no}/preview`, {
        params: {
          code,
        },
      }).then((res) => {
        this.preview = true;
        this.shipment = res.data.data.shipments;
        this.selectedShipment = res.data.data.shipments;
        this.price = res.data.data.price;
      });

  • Try moving the updated hook code inside .then in created hook.

    async created() {
      await axios.get(`/api/pickUp/${no}/preview`, {
        params: {
          code,
        },
      }).then((res) => {
        this.preview = true;
        this.shipment = res.data.data.shipments;
        this.selectedShipment = res.data.data.shipments;
        this.price = res.data.data.price;
        this.$nextTick(() => {
        window.print();
        });
      });
    },