vue 判断浏览器页面宽度是否有变化
时间: 2024-04-24 07:23:14 浏览: 89
在 Vue 中,你可以使用 `@resize` 事件来判断浏览器页面宽度是否有变化。首先,你需要在组件的 `mounted` 生命周期函数中添加一个监听器来监听窗口大小的变化,然后在销毁组件时取消这个监听器。下面是一个示例:
```vue
<template>
<div>
<p v-if="isPageWidthChanged">页面宽度发生了变化</p>
<p v-else>页面宽度没有发生变化</p>
</div>
</template>
<script>
export default {
data() {
return {
isPageWidthChanged: false,
windowWidth: window.innerWidth
};
},
mounted() {
window.addEventListener("resize", this.handleResize);
},
beforeDestroy() {
window.removeEventListener("resize", this.handleResize);
},
methods: {
handleResize() {
if (window.innerWidth !== this.windowWidth) {
this.isPageWidthChanged = true;
this.windowWidth = window.innerWidth;
} else {
this.isPageWidthChanged = false;
}
}
}
};
</script>
```
在上面的示例中,我们通过比较当前窗口的宽度 `window.innerWidth` 和之前保存的窗口宽度 `this.windowWidth` 来判断页面宽度是否有变化。如果宽度发生了变化,我们将 `isPageWidthChanged` 设置为 `true`,并更新 `this.windowWidth` 的值。如果宽度没有变化,我们将 `isPageWidthChanged` 设置为 `false`。根据 `isPageWidthChanged` 的值,我们可以在模板中展示相应的内容。
希望对你有所帮助!如果还有其他问题,请随时提问。
阅读全文
相关推荐


















