正常情况下想要实时获取浏览器窗口的宽度和高度只需要写一个监听浏览器窗口大小改变时获取当前宽度输出即可,在JS里有原生事件,但在vue里很多同学不知道应在将此事件写在哪里,下面给大家提供一个完整的案例。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
<el-button @click="visible = true">时时屏幕宽度:{{windowWidth}}</el-button>
<el-button @click="visible = true">时时屏幕高度:{{windowHeight}}</el-button>
<el-dialog :visible.sync="visible" title="Hello world">
<p>Try Element</p>
</el-dialog>
<div id="main" style="width: 100%;height:400px;"></div>
<div id="main2" style="width: 100%;height:400px;"></div>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.0.0-alpha.1/echarts.min.js"></script>
<script>
var myChart;
var myChart2;
new Vue({
el: '#app',
data: function() {
return {
visible: false,
windowWidth: document.documentElement.clientWidth, //实时屏幕宽度
windowHeight: document.documentElement.clientHeight, //实时屏幕高度
}
},
methods: {
myEcharts() {
// 基于准备好的dom,初始化echarts实例
// myChart = this.$echarts.init(document.getElementById('main')); //VUE脚手架模块化全局引入echarts时的写法
myChart = echarts.init(document.getElementById('main')); //引入CDN echarts链接或在VUE脚手架模块化时在当前页面按需导入echarts时的写法
myChart2 = echarts.init(document.getElementById('main2'));
// 指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
myChart2.setOption(option);
}
},
mounted() {
let that = this;
this.myEcharts();
window.onresize = () => {
return (() => {
window.fullHeight = document.documentElement.clientHeight;
window.fullWidth = document.documentElement.clientWidth;
that.windowHeight = window.fullHeight; // 高
that.windowWidth = window.fullWidth; // 宽
console.log("实时屏幕高度:", that.windowHeight);
console.log("实时屏幕宽度:", that.windowWidth);
myChart.resize();
myChart2.resize();
})()
};
}
})
</script>
</html>
效果图: