How to get the correct width (height) of an element in vue

< H2 > 1. Problem: unable to get the correct width of the element < / H2 >

first look at the picture

clipboard.png
:

  1. canvas 1490px
  2. 740px

2.

canvas

3.

  1. vue , canvas
    ...
  2. (4)

4.

  1. clipboard.png

  2. , canvas

    clipboard.png

  3. vue-cli, , canvas

    clipboard.png

    clipboard.png

  4. add
    set the browser to non-full screen state, and then change the size of the browser. canvas elements will also return to the container
< H2 > 5. A fact < / H2 >

although there is a problem with the above, the first picture shows that the browser has obtained 740px

with the correct width of the element. < H2 > 6. A solution < / H2 >

adding a delay can solve the problem, but it doesn"t feel good. I"m looking forward to a better solution

.
export const setCanvasWidth = that => {
  setTimeout(() => {
    const elWidthValue = that.$refs.el.offsetWidth;
    that.canvasWidth = `${elWidthValue}`; // props need String
  }, 300);
};
Oct.19,2021

has the subject ever tried to get the height of the parent element through $el when the page is rendered in $nextTick, and then change the width attribute of canvas?


try the getComputedStyle method


I usually use instruction binding to trigger the element. The trigger of the instruction must be executed after rendering.


you can try $nextTick

Menu