vue中实时监听浏览器窗口变化,达到自适应

 data() {
    return {
      // 浏览器窗口大小
      // document.body.clientWidth
      timer: false,
      screenWidth: document.body.clientWidth,
    }
}
mounted() {
    const _this = this;
    // 画echars
    // 监听浏览器窗口变化
    window.onresize = function() {
      // console.log("agag")
      return (() => {
        window.screenWidth = document.body.clientWidth;
        _this.screenWidth = window.screenWidth;
      })();
    };
  },

又是使用window.onresize不管用,改为使用window.addEventListener("resize", function () {})即可

window.addEventListener("resize", function () {
    this.screenWidth = document.body.clientWidth;
    this.screenHeight = document.body.clientHeight;
});
watch: {
    screenWidth: {
      immediate: true,
      handler: function(newVal) {
     // 为了避免频繁触发resize函数导致页面卡顿,使用定时器
        if (!this.timer) {
          this.screenWidth = newVal;
          this.timer = true;
          let _this = this;
          setTimeout(() => {
             //在这里做有关浏览器变化时需要做的操作
            _this.timer = false;
          }, 400);
        }
        // if(newVal)
      }
    }
  },

参考:https://blog.csdn.net/weixin_34072458/article/details/88738824

猜你喜欢

转载自blog.csdn.net/qq_41687299/article/details/107211543