监听浏览器宽度(clientWidth)
vue组件中动态获取浏览器宽度,使用如下方式:
- 在data中声明
clientWidth
变量:
data() {
return {
clientWidth: 0
}
}
- 初始化,可以在created中实现:
created() {
this.windowWidth(document.documentElement.clientWidth)
}
methods: {
windowWidth(value) {
this.clientWidth= value
}
},
- 当组件挂载后,调用js的
onresize
方法:
mounted() {
const _this = this;
window.onresize = () => {
return (() => {
_this.clientWidth= `${document.documentElement.clientWidth}`
})()
}
}
- 在watch中监听高度变化
watch: {
clientWidth(val) {
if(!this.timer) {
this.clientWidth= val
this.timer = true
let _this = this
setTimeout(function () {
_this.timer = false
}, 500)
}
this.windowWidth(val);
}
}