vue怎么监听元素尺寸变化?

页面上有canvas元素,同时页面是百分比布局的。
所以页面的尺寸会变化,canvas需要响应重绘。
本来监听onresize方法可以重绘,但是页面还有其他操作,比如隐藏部分元素、全屏等。
所以能不能直接监听canvas的父层元素canvas-wrap的尺寸来重绘呢?

<div id="canvas-wrap">
    <canvas></canvas>
</div>
阅读 25.1k
3 个回答

css-element-queries
比较成熟的解决方案

当然更简单的可以自己写个指令进行轮询

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__);
    },
  });

使用方式

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

这样轮询到div的width,height发生变化就会触发redraw事件了,directive是随手写的,测了下有效,没实用过,只提供个思路

配合着Mutation Observer

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题