1、js监听页面宽度进行对数据的切换操作
当窗口大小发生改变时,上述代码还会动态更新 isWidth
的值。如果窗口宽度缩小到不大于375像素,则将 isWidth
设置为 false
,反之则设置为 true
。同时,在组件卸载时会清理事件监听器,以避免内存泄漏。
let isWidth = ref(true)
onMounted(() => {
if (document.body.clientWidth <= 500) {
isWidth.value = false
} else {
isWidth.value = true
}
// 添加窗口大小改变监听器
window.addEventListener('resize', () => {
if (document.body.clientWidth <= 500) {
isWidth.value = false
} else {
isWidth.value = true
}
});
// 组件卸载时移除事件监听器
return () => {
window.removeEventListener('resize', () => { });
};
});
监听页面变换,切换路由路径
onMounted(() => {
handleResize(); // 初始化时判断一次
// 添加窗口大小改变监听器
const resizeListener = () => {
handleResize();
};
window.addEventListener('resize', resizeListener);
// 组件卸载时移除事件监听器
onBeforeUnmount(() => { // 在 Vue3 中推荐使用 onBeforeUnmount 替换返回的清理函数
window.removeEventListener('resize', resizeListener);
});
});
const handleResize = () => {
if (document.body.clientWidth <= 500) {
router.push('/verify/login');
} else {
router.push('/');
}
}
2、css监听页面宽度进行对css直接在样式覆盖(媒体查询)
当屏幕宽度小于或等于 480px(通常对应移动端或其他小屏幕设备)时,.large
类的样式会改变。此时图片的高度变为 60px,并且 margin 设置为 0,这样在小屏幕上图片会变得更紧凑,并且消除外边距以优化布局。
<template>
<img class="large" :src="largeTwoImage" />
</template>
<style>
// PC 样式
.large {
height: 240px;
width: 100%;
}
// 移动端 样式
@media screen and (max-width: 480px) {
.large {
height: 60px;
margin: 0;
}
}
</style>