计算属性对 VueJS 中的 window.innerwidth 有反应 [英] Computed property reactive to window.innerwidth in VueJS
本文介绍了计算属性对 VueJS 中的 window.innerwidth 有反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上,我需要的是一个计算属性,当 window.innerwidth
等于或低于 768px 和 false
时返回 true
高于 768px.
Basically, what I need is a computed property that returns true
when the window.innerwidth
is equal or lower than 768px and false
when it's higher than 768px.
我做了什么:
computed: {
isMobile() {
if (window.innerWidth <= 768) {
return true
}
return false
}
}
但是这只计算该属性一次,如果我稍后调整窗口大小,它不会对该更改做出反应.我能做什么?
But that computes that property only once, and if I resize the window later, it doesn't react to that change. What can I do?
推荐答案
像这样向窗口添加一个事件监听器:
Add an eventlistener to the window like so:
new Vue({
el: "#app",
data() { return { windowWidth: window.innerWidth } },
mounted() {
window.addEventListener('resize', () => {
this.windowWidth = window.innerWidth
console.log(this.isMobile)
})
},
computed: {
isMobile() {
return this.windowWidth <= 768
}
}
})
这篇关于计算属性对 VueJS 中的 window.innerwidth 有反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文