VueJs监听window.resize方法示例
作者:ailongyang 时间:2024-04-29 13:09:41
Vuejs 本身就是一个 MVVM 的框架。
但是在监听 window 上的 事件 时,往往会显得 力不从心。
比如 这次是 window.resize
恩,我做之前也是百度了一下。看到大家伙都为这个问题而发愁。
问题: 今天我也 遇到了这样一个问题, 是关于canvas 自适应。 根据窗口的变化去变化 canvas 的宽度
备注: 重要的问题说三遍 解决 框架内的bug 先说 框架 版本 版本 版本 (这里用的 Vue 2.x 、ES6)
解决方案:
第一步: 先在 data 中去 定义 一个记录宽度是 属性
data: {
screenWidth: document.body.clientWidth // 这里是给到了一个默认值 (这个很重要)
}
第二步: 我们需要 讲 reisze 事件在 vue mounted 的时候 去挂载一下它的方法
mounted () {
const that = this
window.onresize = () => {
return (() => {
window.screenWidth = document.body.clientWidth
that.screenWidth = window.screenWidth
})()
}
}
第三步: watch 去监听这个 属性值的变化,如果发生变化则讲这个val 传递给 this.screenWidth
watch: {
screenWidth (val) {
this.screenWidth = val
}
}
第四步:优化 因为 频繁 触发 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)
}
}
}
最后一步: 去看看你想要的结果吧~
来源:http://blog.csdn.net/ailongyang/article/details/54755073
标签:Vue,监听,window.resize
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Pandas实现聚合运算agg()的示例代码
2023-09-27 12:35:49
![](https://img.aspxhome.com/file/2023/2/86162_0s.png)
golang进程内存控制避免docker内oom
2024-05-09 09:47:11
![](https://img.aspxhome.com/file/2023/6/127336_0s.png)
asp自动采集程序
2009-02-04 10:11:00
Python从数据库读取大量数据批量写入文件的方法
2024-01-27 14:48:10
CentOS7中使用shell脚本安装python3.8环境(推荐)
2022-08-24 17:04:24
一些SQL查询语法参考
2007-10-14 11:56:00
JavaScript判断对象是否为数组
2024-04-22 22:42:14
详解 MySQL的FreeList机制
2024-01-28 13:56:44
![](https://img.aspxhome.com/file/2023/6/74856_0s.png)
一文搞懂Go Exec 僵尸与孤儿进程
2023-10-21 07:14:07
Python使用PDFMiner解析PDF代码实例
2023-03-30 06:56:45
![](https://img.aspxhome.com/file/2023/7/98927_0s.png)
python中pass语句用法实例分析
2021-08-12 01:49:13
sql2005 存储过程分页示例代码
2024-01-13 03:09:06
mysql生成指定位数的随机数及批量生成随机数的方法
2024-01-16 18:22:22
![](https://img.aspxhome.com/file/2023/8/119758_0s.png)
一文详解Python如何优雅地对数据进行分组
2022-05-20 01:10:15
DHTML 打造 Picture Spelling
2013-08-22 17:01:53
你需要理解的关于MySQL的锁知识
2024-01-21 05:17:11
![](https://img.aspxhome.com/file/2023/1/100331_0s.png)
Python numpy中的ndarray介绍
2022-11-06 19:17:59
![](https://img.aspxhome.com/file/2023/8/130958_0s.png)
浅析pandas随机排列与随机抽样
2022-03-29 21:19:00
python基本语法练习实例
2021-02-25 06:50:07
一篇文章带你了解Python中的类
2022-10-11 19:46:18
![](https://img.aspxhome.com/file/2023/8/101228_0s.png)