标签:来源 lin 部分 define one 情况 eve char win
<template>
<div class="chart"></div>
</template>
<script>
import { merge, isEmpty } from "lodash";
import echart from "echarts";
import { BASIC_OPTION, EMPTY_OPTION } from "./default_option";
export default {
props: {
// 业务数据
dataList: {
type: Array,
default: () => []
},
// 特殊的样式定制
extraOption: {
type: Object,
default: () => ({})
}
},
data() {
return {
chart: null
};
},
methods: {
/**
* 将业务数据加入到基础样式配置中
* @returns {Object} 完整的echart配置
*/
assembleDataToOption() {
return merge(
{},
BASIC_OPTION,
{
series: [{ data: this.dataList }]
},
this.extraOption
);
},
/**
* 更新echart视图
*/
updateChartView() {
if (!this.chart) return;
const fullOption = isEmpty(this.dataList)
? EMPTY_OPTION
: this.assembleDataToOption();
this.chart.setOption(fullOption, true);
},
/**
* 当窗口缩放时,echart动态调整自身大小
*/
handleWindowResize() {
if (!this.chart) return;
this.chart.resize();
}
},
watch: {
dataList: {
deep: true,
handler: () => this.updateChartView
}
},
mounted() {
this.chart = echart.init(this.$el);
this.updateChartView();
window.addEventListener("resize", this.handleWindowResize);
},
beforeDestroy() {
window.removeEventListener("resize", this.handleWindowResize);
}
};
</script>
<style lang="less" scoped>
.chart {
width: 100%;
height: 100%;
}
</style>
merge
,它表示递归合并来源对象自身和继承的可枚举属性到目标对象。后续的来源对象属性会覆盖之前同名的属性isEmpty
,当我传入的业务数据为空时,比如空数组[]
、undefined
、null
时,都会被认为这是一个无数据的情况,这时候我们就选用一个空状态的echarts配置,即EMPTY_OPTION
querySelector
选择器去选择一个类或者是用Math.random
生成的id,因为这两者都不是绝对可靠的,我直接使用当前vue示例关联的根DOM 元素$el
resize
方法,使echarts图形不会变形setOption
方法的第二个参数表示传入的新option是否不与之前的旧option进行合并,默认居然是false,即合并。这显然不行,我们需要每次的业务配置都是完全独立的BASIC_OPTION
,异常情况下(数据为空)的EMPTY_OPTION
,如下:<template>
<div class="echart-wrapper">
<chart-pie :data-list="pieData" :extra-option="option" />
</div>
</template>
<script>
import ChartPie from "@/components/echarts/echart_pie/EchartPie.vue";
export default {
name: "home",
data() {
return {
// 业务数据
pieData: [
{
name: "西瓜",
value: 20
},
{
name: "橘子",
value: 13
},
{
name: "杨桃",
value: 33
}
],
// 定制化配置覆盖默认配置
option: {
color: ["#e033f7", "#15c28e", "#2267e6"]
}
};
},
components: {
ChartPie
}
};
</script>
<style lang="less" scoped>
.echart-wrapper {
width: 300px;
height: 300px;
margin: 10px auto;
}
</style>
当数据正常时,效果如下
当无数据时,效果如下
标签:来源 lin 部分 define one 情况 eve char win
原文地址:https://www.cnblogs.com/zhangnan35/p/12680038.html