Vue3 获取屏幕尺寸并显示
时间: 2023-09-26 16:09:27 浏览: 83
在 Vue 3 中,你可以通过 `window.innerWidth` 和 `window.innerHeight` 属性获取屏幕的宽度和高度。然后在模板中使用这些值来进行渲染。
以下是一个示例代码:
```
<template>
<div>
<p>屏幕宽度:{{ screenWidth }}px</p>
<p>屏幕高度:{{ screenHeight }}px</p>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const screenWidth = ref(window.innerWidth)
const screenHeight = ref(window.innerHeight)
window.addEventListener('resize', () => {
screenWidth.value = window.innerWidth
screenHeight.value = window.innerHeight
})
return {
screenWidth,
screenHeight,
}
},
}
</script>
```
在上面的代码中,我们使用了 `ref` 方法来创建了两个响应式变量 `screenWidth` 和 `screenHeight`,并将它们的默认值设置为 `window.innerWidth` 和 `window.innerHeight`。然后我们在 `setup` 函数中添加了一个 `resize` 事件监听器,当窗口大小改变时,更新 `screenWidth` 和 `screenHeight` 的值。
在模板中,我们使用了插值表达式来显示 `screenWidth` 和 `screenHeight` 的值。这样就能够实时显示屏幕的尺寸了。
希望这个回答能够帮助你!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)