为了实现页面的宽度和高度自适应,有时候我们需要根据窗口的变化去改变页内元素的宽高,而 VUE 作为一款轻量级的 MVVM 框架,在监听和处理 BOM 事件时需要在指定的区域进行处理,这里记录两种常用而且比较简单的方法。
方案一:
1.在 data 中去 定义 一个记录宽度是 属性
data: { return { screenWidth: document.body.clientWidth // 设置默认值 } }
2.在 vue mounted 的时候 去挂载一下 window.onresize 方法
mounted () { const that = this window.onresize = () => { return (() => { window.screenWidth = document.body.clientWidth that.screenWidth = window.screenWidth })() } }
3.watch 去监听这个 属性值的变化,如果发生变化则讲这个 val 传递给 this.screenWidth
watch: { screenWidth (val) { this.screenWidth = val } }
4.优化因为频繁触 resize 函数,导致页面卡顿的问题
watch: { screenWidth (val) { if (!this.timer) { this.screenWidth = val this.timer = true let that = this setTimeout(function () { // that.screenWidth = that.$store.state.canvasWidth console.log(that.screenWidth) that.init() that.timer = false }, 400) } } }
方案二(推荐使用):
原理:在 mounted 钩子中 全局监听 resize 事件,然后绑定的函数再做具体的处理。
data(){ return { clientHeight: document.body.clientHeight, }, }, mounted() { // 在DOM渲染数据时,设置下区域高度为浏览器可视区域高度. this.clientHeight = document.body.clientHeight; // 监听window的resize事件.在浏览器窗口变化时再设置下区域高度. const _this = this; window.onresize = function temp() { _this.clientHeight = document.body.clientHeight; }; },
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于