VUE 获取窗口宽度的实时变化

2021/7/11 10:4:15 | 阅2546 来源:好空间网络 [打印] [关闭]
 

VUE 获取窗口宽度的实时变化

export default {
  name: 'order',
  data() {
    return {
      windowWidth: 0, // 窗口的宽度
    }
  },
  components: {
    // 组件
  },
  computed: {
    // 计算属性,里面是个方法
  },
  methods: {
    
    /**
     * 监听窗口的宽度
     */
    searchFormWidth() {
      this.windowWidth = window.innerWidth
      console.log('this.windowWidth:', this.windowWidth)

      // if (w <= 1280) {
      //   this.searchWidth = 280
      // } else if (w < 1920) {
      //   this.searchWidth = ((w - 1280) * 80) / 640 + 280
      // } else {
      //   this.searchWidth = 360
      // }
    }
  },
  mounted() {
  
    /**
     * 监听窗口宽度
     */
    this.searchFormWidth() // 组件初始化的时候不会触发onresize事件,这里强制执行一次
    window.onresize = () => {
      if (!this.timer) {
        // 使用节流机制,降低函数被触发的频率
        this.timer = true
        var that = this // 匿名函数的执行环境具有全局性,为防止this丢失这里用that变量保存一下
        setTimeout(function() {
          that.searchFormWidth()
          that.timer = false
        }, 400)
      }
    }
  },
  destroyed() {
    // 组件销毁后解绑事件
    window.onresize = null
  }
}


经营许可证ICP:皖B2-20100052 公司邮箱:zcdnsz@jspkongjian.net
Copyright © 2004-2015, 安徽好空间网络科技有限公司 版权所有 , 本站素材部分来源于网络,如有侵权请告知删除。