最近做eCharts图表,但是有个需求就是想要适配不同的屏幕,但是发现eCharts不能自己进行适配,然后就上网进行翻阅,现在进行总结一下
首先我把eCharts单独提到一个组件中

在需要的组件中进行引入
下面看一下Echarts中index.vue中的代码
<template>
<div
id="myChart"
:style="{width: '600px', height: '400px'}"
></div>
</template>
<script>
export default {
name: 'eCharts',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
mounted () {
this.drawLine();
},
methods: {
drawLine () {
// 基于准备好的dom,初始化echarts实例
var myChart = this.$echarts.init(document.getElementById('myChart'))
// 绘制图表
myChart.setOption({
title: { text: '销售' },
legend: { type: 'scroll' },
tooltip: {},
dataset: {
source: [
['product', '金额', '毛利', '订单数'],
['日销售', 43.3, 85.8, 93.7],
['周销售', 83.1, 73.4, 55.1],
['月销售', 86.4, 65.2, 82.5],
]
},
xAxis: { type: 'category' },
yAxis: {},
// Declare several bar series, each will be mapped
// to a column of dataset.source by default.
series: [
{ type: 'bar' },
{ type: 'bar' },
{ type: 'bar' }
]
})
myChart.resize();
},
}
}
</script>
<style lang="less" scoped>
@media screen and (max-width: 780px) {
#main {
width: 100%;
height: 300px;
}
}
</style>
官网给出的案例不能进行自适应,但可以进行基本的展示,
需要进行自适应需要进行屏幕的高度的计算
代码如下
<template>
<div
id="myChart"
ref="myChart"
style="width:90%;"
></div>
</template>
<script>
import echarts from 'echarts'
import { type } from 'os';
export default {
name: 'echarts',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
mounted () {
// this.fn()
// this.drawLine()
this.$nextTick(() => {
this.loadBugChart()
})
},
methods: {
loadBugChart () {
var domBugChart = this.$refs.myChart; //获取DOM节点
//自适应宽高
var bugChartContainer = function () {
if (domBugChart) {
domBugChart.style.width = 66 + "vw";
domBugChart.style.height = 70 + "vh";
}
}
bugChartContainer();
var bugChart = echarts.init(domBugChart);
let option = {
title: {},
legend: { type: 'scroll' },
tooltip: {},
dataset: {
source: [
['product', '金额', '毛利', '订单数'],
['日销售', 43.3, 85.8, 93.7],
['周销售', 83.1, 73.4, 55.1],
['月销售', 86.4, 65.2, 82.5],
]
},
xAxis: { type: 'category' },
yAxis: {},
series: [
{ type: 'bar' },
{ type: 'bar' },
{ type: 'bar' }
]
}
bugChart.setOption(option);
},
}
}
</script>
<style lang="less" scoped>
@media screen and (max-width: 780px) {
#main {
width: 100%;
height: 300px;
}
}
</style>
下面顺带说一下vw与vh是什么吧
是前端CSS3使用vw和vh视口单位实现自适应
vw ( Viewport Width)
vh ( Viewport Height)
系统会将视口的宽度和高度分为100份
1vw 等于视口宽度的1%
1vh 等于视口高度的1%
视口单位区别于%单位,视口单位是依赖于视口的尺寸,根据视口尺寸的百分比来定义的;而%单位则是依赖于元素的父元素。

本文总结了如何使eCharts图表适应不同屏幕。由于eCharts默认不支持自动适配,作者通过引入组件并调整屏幕高度计算来实现自适应效果。文中还介绍了CSS3的视口单位vw和vh,它们分别代表视口宽度和高度的百分比,用于实现基于视口尺寸的自适应布局。
1392

被折叠的 条评论
为什么被折叠?



