首先,頁面初始化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>
嗯。就醬~~