vue里面使用echarts实现根据浏览器屏幕大小自适应
1- 安装 echarts 依赖npm install echarts -S2- 创建图表全局引入在main.js 中写import echarts from 'echarts'Vue.prototype.$echarts = echarts3- 在对应的页面里面写echarts图表示例1,新建echarts_demo.vue<template><d...
·
1- 安装 echarts 依赖
npm install echarts -S
2- 创建图表全局引入
在main.js 中写
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
3- 在对应的页面里面写echarts图表
示例
1,新建echarts_demo.vue
<template>
<div id="myChart" :style="{width: '100%', height: '600px'}"></div>
</template>
<script>
export default {
name: "hello",
data() {
return {
msg: "Welcome to Your Vue.js App"
};
},
mounted() {
this.day_init();
},
methods: {
//实现自适应
day_init() {
const self = this; //因为箭头函数会改变this指向,指向windows。所以先把this保存
var todaypieId = document.getElementById("myEchart");
if (!todaypieId) {
return false;
} else {
setTimeout(() => {
window.onresize = function() {
// self.chart = echarts.init(self.$refs.myEchart);
self.chart_today = echarts.init(
todaypieId
);
self.chart_today.resize();
};
}, 20);
}
},
drawLine() {
// 基于准备好的dom,初始化echarts实例
let myChart = this.$echarts.init(document.getElementById("myChart"));
// 绘制图表
myChart.setOption({
tooltip: {
trigger: "axis",
axisPointer: {
// 坐标轴指示器,坐标轴触发有效
type: "shadow" // 默认为直线,可选为:'line' | 'shadow'
}
},
legend: {
data: [
"西瓜",
"菠萝",
"苹果",
"榴莲",
"草莓",
"橘子"
]
},
grid: {
left: "3%",
right: "4%",
bottom: "3%",
containLabel: true
},
xAxis: [
{
type: "category",
data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
}
],
yAxis: [
{
type: "value"
}
],
series: [
{
name: "西瓜",
type: "bar",
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: "菠萝",
type: "bar",
stack: "",
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: "苹果",
type: "bar",
stack: "",
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: "榴莲",
type: "bar",
stack: "",
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: "草莓",
type: "bar",
data: [862, 1018, 964, 1026, 1679, 1600, 1570],
markLine: {
lineStyle: {
normal: {
type: "dashed"
}
},
data: [[{ type: "min" }, { type: "max" }]]
}
},
{
name: "橘子",
type: "bar",
barWidth: 5,
stack: "",
data: [620, 732, 701, 734, 1090, 1130, 1120]
}
]
});
}
}
};
</script>
<style lang="less">
</style>
执行成功后会控制台会出现错误
由于echarts图形ID是由后台传输过来的,并且是根据图形数据一起传过来,出现了图形容器还未生成,但是数据已经来了,这样就会出现这个问题:找不到图形容器
解决办法
(1)如果图形数据和图形ID一起传输过来,先保证图形容器已存在,后生成图形;可以利用定时器延后图形数据
(2)可以将图形数据和图形ID分为两个请求接口,分别同步进行,先保证图形容器存在,然后再生成图形
代码添加判断
var pieId = document.getElementById(‘myChart’);
if (!pieId){
return false;
}
var pie = echarts.init(pieId)
更多推荐
已为社区贡献15条内容
所有评论(0)