vue监听窗口大小变化 自动缩放
时间: 2023-05-10 11:01:42 浏览: 2209
Vue可以通过监听窗口大小变化来实现自动缩放的效果。在Vue中,可以使用@resize
事件来监听窗口大小变化,并在事件处理函数中更新组件的样式或其他属性。
例如,在一个需要自适应的组件中,可以使用如下代码来实现:
<template>
<div class="container" :style="{ width: containerWidth + 'px', height: containerHeight + 'px' }">
<!-- 组件内容 -->
</div>
</template>
<script>
export default {
data() {
return {
containerWidth: window.innerWidth,
containerHeight: window.innerHeight
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.containerWidth = window.innerWidth
this.containerHeight = window.innerHeight
}
}
}
</script>
在上述代码中,我们在组件中定义了一个container
容器,使用:style
绑定了容器的宽度和高度,这样容器的大小会随着窗口的大小变化而自动调整。在组件的data
属性中,我们初始化了容器的宽度和高度为当前窗口的宽度和高度。在mounted
中,我们通过window.addEventListener
添加了一个窗口大小变化的事件监听器,监听到窗口大小变化的时候会触发handleResize
方法来更新容器的宽度和高度。在beforeDestroy
中,我们通过window.removeEventListener
移除了监听器,以免在组件销毁的时候出现问题。
通过上述代码,我们就可以在Vue中实现窗口大小变化自动缩放的效果了。
相关推荐

















