vue3监听屏幕宽度
时间: 2024-04-24 13:20:45 浏览: 203
在Vue 3中,可以使用watch
属性来监听屏幕宽度的变化。具体步骤如下:
- 首先,在Vue组件中定义一个
data
属性来保存屏幕宽度的值,例如screenWidth
。 - 在
mounted
生命周期钩子函数中,使用window.innerWidth
获取当前屏幕的宽度,并将其赋值给screenWidth
。 - 在
watch
属性中监听screenWidth
的变化,当屏幕宽度发生改变时,执行相应的逻辑。
下面是一个示例代码:
<template>
<div>
<p>当前屏幕宽度:{{ screenWidth }}</p>
</div>
</template>
<script>
export default {
data() {
return {
screenWidth: 0
};
},
mounted() {
this.screenWidth = window.innerWidth;
window.addEventListener('resize', this.handleResize);
},
beforeUnmount() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.screenWidth = window.innerWidth;
}
}
};
</script>
在上述代码中,我们通过mounted
钩子函数初始化屏幕宽度,并在窗口大小改变时通过handleResize
方法更新screenWidth
的值。同时,在组件销毁前,我们需要移除窗口大小改变事件的监听。
相关推荐


















