思路:
- data里面:变量screenWidths
timer: false,
screenWidth: document.body.clientWidth,
- addEventListener监听resize事件
- 只要resize事件一被监听就会被触发:无论是在mounted、还是做了防抖都不能阻止addEventListener监听到事件并触发事件。
- watch:可以被防抖。
- 所以我们要用触发resize事件拿到document.body.clientWidth,然后不断的给data的screenWidths赋值。
// 监听screenWidth,改变data的screenWidth
window.addEventListener('resize', () => {
const screenWidths = document.body.clientWidth
this.screenWidth = screenWidths
})
- watch监听:注意防抖,防止不断被触发(lodash)
watch: {
/*监听页面*/
screenWidth(val) {
// 为了避免频繁触发resize函数导致页面卡顿,使用定时器
if (!this.timer) {
// 一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
this.screenWidth = val
this.timer = true
setTimeout(() => {
let screenWidth = this.screenWidth
if (screenWidth < 1530) {
this.$refs.fromButton.$el.style.marginLeft = 0
console.log(screenWidth)
} else if (screenWidth >= 1536) {
console.log(1530)
this.$refs.fromButton.$el.style.marginLeft = 14.58 + 'rem'
}
console.log(this.$refs.fromButton.$el.style.marginLeft)
this.timer = false
}, 600)
}
},
},