上面案例换成vue3写法
时间: 2025-08-30 14:54:22 AIGC 浏览: 14
<think>
我们有一个任务:将JavaScript中的`window.addEventListener('resize', updateScale)`转换为Vue 3的写法。
在Vue 3中,我们通常使用组合式API(Composition API)和生命周期钩子来管理事件监听。
关键点:
1. 在Vue组件中,我们希望在组件挂载后开始监听窗口的resize事件,并在组件卸载时移除监听,以避免内存泄漏。
2. Vue 3中,我们可以使用`onMounted`和`onUnmounted`生命周期钩子。
3. 我们使用`window.addEventListener`添加事件监听,并在卸载时使用`window.removeEventListener`移除。
步骤:
a. 在setup()函数中(或者使用`<script setup>`语法糖)引入生命周期钩子函数。
b. 在`onMounted`钩子中添加事件监听。
c. 在`onUnmounted`钩子中移除事件监听。
另外,我们可能还需要考虑性能优化,比如使用防抖(debounce)或节流(throttle)来避免resize事件触发过于频繁。
示例代码:
使用`<script setup>`语法(推荐):
```vue
<script setup>
import { onMounted, onUnmounted } from 'vue'
// 定义updateScale函数
function updateScale() {
// 根据窗口大小更新缩放比例的逻辑
console.log('窗口大小改变了')
}
// 添加事件监听
onMounted(() => {
window.addEventListener('resize', updateScale)
})
// 移除事件监听
onUnmounted(() => {
window.removeEventListener('resize', updateScale)
})
</script>
```
或者,使用选项式API(Options API)的写法(Vue 3也支持):
```vue
<script>
import { onMounted, onUnmounted } from 'vue'
export default {
setup() {
function updateScale() {
console.log('窗口大小改变了')
}
onMounted(() => {
window.addEventListener('resize', updateScale)
})
onUnmounted(() => {
window.removeEventListener('resize', updateScale)
})
}
}
</script>
```
但是,在选项式API中,我们也可以使用`mounted`和`unmounted`生命周期选项(不引入组合式API):
```vue
<script>
export default {
mounted() {
window.addEventListener('resize', this.updateScale)
},
beforeUnmount() { // Vue 3中卸载前生命周期钩子改名为beforeUnmount
window.removeEventListener('resize', this.updateScale)
},
methods: {
updateScale() {
console.log('窗口大小改变了')
}
}
}
</script>
```
注意:在Vue 3中,销毁生命周期钩子名称发生了变化,原来的`beforeDestroy`和`destroyed`被替换为`beforeUnmount`和`unmounted`(在选项式API中,我们使用`beforeUnmount`和`unmounted`,但是在组合式API中,我们使用`onBeforeUnmount`和`onUnmounted`)。
另外,为了性能考虑,我们可以添加防抖或节流。这里以节流为例,我们可以使用lodash的throttle或者自己实现一个简单的节流函数。
例如,使用lodash:
```vue
<script setup>
import { onMounted, onUnmounted } from 'vue'
import { throttle } from 'lodash-es'
function updateScale() {
// ...
}
const throttledUpdate = throttle(updateScale, 100)
onMounted(() => {
window.addEventListener('resize', throttledUpdate)
})
onUnmounted(() => {
window.removeEventListener('resize', throttledUpdate)
throttledUpdate.cancel() // 确保取消lodash的节流函数中的定时器
})
</script>
```
自己实现一个简单的节流函数:
```javascript
function throttle(fn, delay) {
let lastCall = 0
return function(...args) {
const now = new Date().getTime()
if (now - lastCall < delay) {
return
}
lastCall = now
return fn(...args)
}
}
```
然后使用这个节流函数包装updateScale。
总结:在Vue 3中,我们使用生命周期钩子来管理事件监听,确保在组件卸载时移除监听器,避免内存泄漏。同时,考虑性能优化,对频繁触发的事件进行节流或防抖处理。
引用说明:
在Vue 3中,生命周期钩子函数有了新的命名,我们可以参考引用[2]中的对应关系:
- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeUnmount -> onBeforeUnmount
- unmounted -> onUnmounted
因此,我们使用onMounted和onUnmounted(组合式API)或者mounted和beforeUnmount(选项式API)来管理事件监听。
注意:在组合式API中,我们没有直接使用beforeDestroy和destroyed,而是使用onBeforeUnmount和onUnmounted(引用[2])。
</think>
### 将 `window.addEventListener('resize', updateScale)` 转换为 Vue 3 写法
在 Vue 3 中,推荐使用组合式 API 管理事件监听器,以下是完整实现方案:
#### 1. 基础实现(组合式 API)✅
```vue
<script setup>
import { onMounted, onBeforeUnmount } from 'vue'
function updateScale() {
// 实现缩放逻辑,例如:
const scale = window.innerWidth / 1920
document.getElementById('container').style.transform = `scale(${scale})`
}
onMounted(() => {
window.addEventListener('resize', updateScale)
updateScale() // 初始执行一次
})
onBeforeUnmount(() => {
window.removeEventListener('resize', updateScale)
})
</script>
```
#### 2. 优化方案:添加节流处理(推荐)🔥
```vue
<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'
const scaleValue = ref(1)
// 节流函数优化性能
function throttle(fn, delay = 100) {
let timer = null
return (...args) => {
if (!timer) {
timer = setTimeout(() => {
fn(...args)
timer = null
}, delay)
}
}
}
const updateScale = throttle(() => {
scaleValue.value = Math.min(
window.innerWidth / 1920,
window.innerHeight / 1080
)
})
// 生命周期管理
onMounted(() => {
window.addEventListener('resize', updateScale)
updateScale()
})
onBeforeUnmount(() => {
window.removeEventListener('resize', updateScale)
})
</script>
<template>
<div :style="{ transform: `scale(${scaleValue})` }">
<!-- 内容区域 -->
</div>
</template>
```
#### 3. 选项式 API 写法(兼容 Vue 2)🔄
```vue
<script>
export default {
mounted() {
window.addEventListener('resize', this.updateScale)
this.updateScale()
},
beforeUnmount() {
window.removeEventListener('resize', this.updateScale)
},
methods: {
updateScale() {
// 缩放逻辑实现
}
}
}
</script>
```
#### 4. 使用 VueUse 库简化(推荐最佳实践)✨
```vue
<script setup>
import { useWindowSize } from '@vueuse/core'
import { watch } from 'vue'
const { width, height } = useWindowSize()
watch([width, height], () => {
const scale = Math.min(width.value / 1920, height.value / 1080)
document.documentElement.style.setProperty('--scale-factor', scale)
})
</script>
<style>
:root {
--scale-factor: 1;
}
.container {
transform: scale(var(--scale-factor));
}
</style>
```
#### 关键点说明:
1. **生命周期管理**:
- `onMounted` 添加监听(对应 Vue 2 的 `mounted`)
- `onBeforeUnmount` 移除监听(对应 Vue 2 的 `beforeDestroy`)[^2]
2. **性能优化**:
- 必须添加节流/防抖避免高频触发
- 使用 `ref` 响应式变量驱动视图更新
3. **最佳实践**:
- 推荐使用 VueUse 的 `useWindowSize` 组合函数
- CSS 变量实现缩放更高效(避免 JS 操作 DOM)
> Vue 3 的响应式系统通过 Proxy 实现[^1],结合组合式 API 可更优雅地管理事件监听器,避免内存泄漏问题。
---
### 相关问题
1. Vue 3 中如何实现组件级别的响应式尺寸监听?
2. 使用 VueUse 的 `useWindowSize` 有哪些额外优势?
3. 移动端横竖屏切换时如何优化缩放性能?
4. Vue 3 中如何为多个组件共享同一个 resize 事件处理器?
阅读全文
相关推荐



















