<template>
<div :style="{ height: windowHeight+ 'px' }">1</div>
</template>
方法一: js
export default {
data(){
return{
windowWidth: document.documentElement.clientWidth, //实时屏幕宽度
windowHeight: document.documentElement.clientHeight, //实时屏幕高度
}
},
// <!--在watch中监听实时宽高-->
watch: {
windowHeight (val) {
let that = this;
console.log("实时屏幕高度:",val, that.windowHeight );
},
windowWidth (val) {
let that = this;
console.log("实时屏幕宽度:",val, that.windowHeight );
}
},
mounted() {
var that = this;
// <!--把window.onresize事件挂在到mounted函数上-->
window.onresize = () => {
return (() => {
window.fullHeight = document.documentElement.clientHeight;
window.fullWidth = document.documentElement.clientWidth;
that.windowHeight = window.fullHeight; // 高
that.windowWidth = window.fullWidth; // 宽
})()
};
},
}
方法二:
使用vue插件 element-resize-detector
第一步:安装
安装命令 npm install --save element-resize-detector
卸载命令 npm uninstall element-resize-detector
第二步:引入
<script>
import elementResizeDetector from "element-resize-detector";
</script>
第三步:使用
export default {
data(){
return{
windowHeight:null,
windowWidth:null,
},
mounted() {
const that = this;
var erd = elementResizeDetector();
erd.listenTo('监听的dom', (element) => { //监听的domdocument.get方法获取
that.windowWidth= element.offsetWidth;
that.windowHeight= element.offsetHeight;
that.$nextTick(() => {
console.log("宽:"+that.windowWidth,"高:"+that.windowHeight)
// 这里填写监听改变后的操作
});
});
},
}