How does vue listen for element size changes?

The

page has a canvas element, and the page is laid out as a percentage.
so the size of the page changes, and canvas needs to be redrawn in response.
the listening onresize method can be redrawn, but there are other actions on the page, such as hiding some elements, full screen, and so on.
so can you directly listen to the size of canvas-wrap, the parent element of canvas, to redraw?

<div id="canvas-wrap">
    <canvas></canvas>
</div>
Feb.16,2022

css-element-queries
A more mature solution

of course, it's easier to write an instruction to poll

.
Vue.directive('resize', {
    bind(el, binding) {
      let width = '', height = '';
      function get() {
        const style = document.defaultView.getComputedStyle(el);
        if (width !== style.width || height !== style.height) {
          binding.value({width, height});
        }
        width = style.width;
        height = style.height;
      }

      el.__vueReize__ = setInterval(get, 200);
    },
    unbind(el) {
      clearInterval(el.__vueReize__);
    },
  });

how to use

<div id="canvas-wrap" v-resize="redraw">
    <canvas></canvas>
</div>

in this way, the width,height polled to div will trigger the redraw event. directive is handwritten, tested to be effective, but has not been used, and only provides an idea

.

cooperates with Mutation Observer Bar


resize intelligently monitors window size changes. I previously wrote a blog that listens to element sizes: https://blog.csdn.net/u010419.

.
Menu