vue3 watch 监听屏幕分辨率变化调用自定义函数
时间: 2023-09-10 11:11:30 浏览: 129
在 Vue3 中,可以使用 watchEffect
监听屏幕分辨率的变化,并调用自定义函数。具体步骤如下:
- 在
setup
函数中引入reactive
和watchEffect
:
import { reactive, watchEffect } from 'vue'
- 定义一个响应式对象
state
,用于存储屏幕分辨率的宽度和高度:
const state = reactive({
screenWidth: window.innerWidth,
screenHeight: window.innerHeight
})
- 使用
watchEffect
监听屏幕分辨率的变化,并在回调函数中调用自定义函数:
watchEffect(() => {
state.screenWidth = window.innerWidth
state.screenHeight = window.innerHeight
// 调用自定义函数
myFunction(state.screenWidth, state.screenHeight)
})
完整代码示例:
<template>
<div>
<p>屏幕宽度:{{ state.screenWidth }}</p>
<p>屏幕高度:{{ state.screenHeight }}</p>
</div>
</template>
<script>
import { reactive, watchEffect } from 'vue'
export default {
setup() {
const state = reactive({
screenWidth: window.innerWidth,
screenHeight: window.innerHeight
})
watchEffect(() => {
state.screenWidth = window.innerWidth
state.screenHeight = window.innerHeight
// 调用自定义函数
myFunction(state.screenWidth, state.screenHeight)
})
function myFunction(screenWidth, screenHeight) {
// 自定义函数内容
console.log(`屏幕分辨率:${screenWidth} x ${screenHeight}`)
}
return {
state
}
}
}
</script>
相关推荐















