解决方案来源https://github.com/lizheng3401/echarts-in-element-doesn-t-work
解决方法:
设置当前key值与v-model绑定的值一致时才加载图表。
话不多说,直接贴码
<template>
<div>
<el-tabs type="card" v-model="activeName">
<el-tab-pane
v-for="item in tabMapOptions"
:label="item.label"
:key="item.key"
:name="item.name"
>
<charts v-if="item.name === activeName"></charts>
</el-tab-pane>
</el-tabs>
</div>
</template>
<script>
import charts from "./charts";
import "../assets/stylesheets/reset.css";
export default {
name: "index",
components: {
charts
},
data() {
return {
activeName: "first",
tabMapOptions: [
{
label: "二楼",
name: "first",
},
{
label: "配电间",
name: "second",
}
]
};
}
};
</script>
charts.vue
<template>
<div :style="{height:height,width:width}"></div>
</template>
<script>
import * as echarts from "echarts";
export default {
name: "charts",
props: {
width: {
type: String,
default: "100%"
},
height: {
type: String,
default: "500px"
}
},
data: function() {
return {
chart: null
};
},
mounted: function() {
this.initChart();
},
beforeDestroy: function() {
if (!this.chart) {
return;
}
this.chart.dispose();
this.chart = null;
},
methods: {
setOptions: function() {
this.chart.setOption({
title: {
text: "二楼"
},
tooltip: {
trigger: "axis",
axisPointer: {
// 坐标轴指示器,坐标轴触发有效
type: "" // 默认为直线,可选为:'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: [22, 48, 53, 5.83]
},
{
name: "乙班",
type: "bar",
data: [6, 9, 16, 20.69]
}
]
});
},
initChart: function() {
this.chart = this.$echarts.init(this.$el);
this.setOptions();
}
}
};
</script>
<style scoped>
</style>