vue实现窗口调大小
Vue 实现窗口大小调整
在 Vue 中实现窗口大小调整功能,可以通过监听浏览器窗口的 resize 事件,并结合 Vue 的响应式特性来动态更新组件状态。
监听窗口大小变化
在 Vue 组件的 mounted 生命周期钩子中,添加 resize 事件监听器。在 beforeDestroy 钩子中移除监听器,避免内存泄漏。
export default {
data() {
return {
windowWidth: window.innerWidth,
windowHeight: window.innerHeight,
};
},
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth;
this.windowHeight = window.innerHeight;
},
},
};
响应式更新 UI
根据窗口大小动态调整 UI 布局或样式。例如,可以通过计算属性或直接绑定样式来实现。
<template>
<div :style="{ fontSize: fontSize + 'px' }">
窗口宽度: {{ windowWidth }}, 高度: {{ windowHeight }}
</div>
</template>
<script>
export default {
computed: {
fontSize() {
return Math.max(12, this.windowWidth / 100);
},
},
};
</script>
使用防抖优化性能
频繁触发 resize 事件可能导致性能问题。可以使用防抖(debounce)函数来限制事件触发的频率。
import { debounce } from 'lodash';
export default {
methods: {
handleResize: debounce(function() {
this.windowWidth = window.innerWidth;
this.windowHeight = window.innerHeight;
}, 200),
},
};
结合 CSS 媒体查询
对于简单的布局调整,可以优先使用 CSS 媒体查询,减少 JavaScript 的介入。
@media (max-width: 600px) {
.container {
flex-direction: column;
}
}
使用 Vue 插件或库
如果需要更复杂的功能,可以考虑使用现成的 Vue 插件或库,例如 vue-resize 或 vue-window-size。
import VueWindowSize from 'vue-window-size';
Vue.use(VueWindowSize);
在组件中直接使用插件提供的属性:
<template>
<div>窗口宽度: {{ $windowWidth }}</div>
</template>






