https://blog.csdn.net/xuaner8786/article/details/81565219
一、在Vue單個頁面運用
<template> <div id="divId"> </div> </template> <script> export default { data() { return { screenWidth: document.documentElement.clientWidth,//屏幕寬度 screenHeight: document.documentElement.clientHeight,//屏幕高度 } }, watch:{ 'screenWidth':function(val){ //監聽屏幕寬度變化 var oIframe = document.getElementById(divId); oIframe.style.width = (Number(val)-120) + 'px'; //'120'是頁面布局調整,可去除 }, 'screenHeight':function(){ //監聽屏幕高度變化 var oIframe = document.getElementById(divId); oIframe.style.height = (Number(val)-120) + 'px'; //'120'是頁面布局調整,可去除 } }, mounted() { var _this = this; window.onresize = function(){ // 定義窗口大小變更通知事件 _this.screenWidth = document.documentElement.clientWidth; //窗口寬度 _this.screenHeight = document.documentElement.clientHeight; //窗口高度 }; } } </script>
二、在項目中全局運用
1、在store.js里定義
let state = { screenWidth:document.documentElement.clientWidth, //屏幕寬度 screenHeight:document.documentElement.clientHeight, //屏幕高度 }
2、在main.vue里掛載window.onresize
mounted() { var _this = this; window.onresize = function(){ // 定義窗口大小變更通知事件 _this.$store.state.screenWidth = document.documentElement.clientWidth; //窗口寬度 _this.$store.state.screenHeight = document.documentElement.clientHeight; //窗口高度 }; }
3、在Vue頁面中監聽
<template> <div id="divId"> </div> </template> <script> export default { data() { return { screenWidth: document.documentElement.clientWidth,//屏幕寬度 screenHeight: document.documentElement.clientHeight,//屏幕高度 } }, watch:{ '$store.state.screenWidth':function(val){ //監聽屏幕寬度變化 var oIframe = document.getElementById(divId); oIframe.style.width = (Number(val)-120) + 'px'; //'120'是頁面布局調整,可去除 }, '$store.state.screenHeight':function(){ //監聽屏幕高度變化 var oIframe = document.getElementById(divId); oIframe.style.height = (Number(val)-120) + 'px'; //'120'是頁面布局調整,可去除 } } } </script>
注意事項
1、在項目中 window.onresize只能掛載一次,在多個頁面中同時掛載 window.onresize時,只有其中一個 window.onresize會起作用
2、避免 window.onresize頻繁掛載(待續)
其他
watch: { screenWidth (val) { if (!this.timer) { this.screenWidth = val this.timer = true let that = this setTimeout(function () { // that.screenWidth = that.$store.state.canvasWidth console.log(that.screenWidth) that.init() that.timer = false }, 400) } } }