首先,页面初始化mounted的时候,通过 document.body.clientWidth 和 document.body.clientHeight 来获取到浏览器的宽和高,然后通过 window.onresize 来监听浏览器窗口的变化,在这里来改变我们的变量宽和高即可。

(created()的时候不行,因为此时document还没有生成)

<template>
<section class="p-10">
<h1> {{ screenWidth }} × {{ screenHeight }} </h1>
</section>
</template>
<script>
export default {
data() {
return {
screenWidth: '',
screenHeight: ''
};
},
mounted() {
this.screenWidth = document.body.clientWidth;
this.screenHeight = document.body.clientHeight;
window.onresize = () => {
return (() => {
this.screenWidth = document.body.clientWidth;
this.screenHeight = document.body.clientHeight;
})();
};
}
}
</script>

<style lang="scss">
</style>