定义图表公共样式是为了统一同一网站各页面图表的基础样式baseOption.js(轴线、区域、高亮样式),统一封装后页面需要直接引入,传入所需参即可覆盖基础样式。以下示例封装图表组件PieChart.vue(此处为饼图,也可自行更改为公共统一组件不区分图表类型)
common.js方法函数库:
// 生成唯一值编码
export function uuid() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0,
v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
baseOption.js文件代码(公共样式引入,为了统一各种图表的基础样式,比如轴线、图各板块颜色,值仅供参考):
export default {
color: [
"#0067E1",
"#0CC1FF",
"#00D1B3",
"#85E814",
"#FFA082",
"#FFB92F",
"#E00065",
"#FA7AE9",
],
tooltip: {},
legend: {
show:false,
orient:'horizontal',
type:'scroll',
pageIconSize:12,
pageIconColor:'#aaa',
pageIconInactiveColor :'#2f4554',
pageTextStyle:{
color:'#999999'
},
itemWidth:20,
itemHeight:12,
top:0,
textStyle:{
color:'#999999'
},
},
grid: {
top: "13%",
left: "3%",
right: "10%",
bottom: "2%",
containLabel: true,
},
xAxis: [
{
axisLine: {
lineStyle: {
color: "rgba(65, 97, 128, 0.15)",
// type: "dashed",
},
},
axisTick: {
show: false,
},
axisLabel: {
interval:0,
color: "#rgba(0, 0, 0, 0.25)",
textStyle: {
fontSize: 10,
}
},
nameTextStyle:{
color:'#999999',
fontSize: 10,
},
},
],
yAxis: [
{
axisLabel: {
color: "#rgba(0, 0, 0, 0.25)",
textStyle: {
fontSize: 11,
},
},
axisLine: {
lineStyle: {
color: "rgba(65, 97, 128, 0.15)",
},
},
splitLine: {
lineStyle: {
color: "rgba(65, 97, 128, 0.15)",
},
},
axisTick: {
show: false,
},
nameTextStyle:{
color:'#999999',
fontSize: 10,
padding:[0,20,0,0]
},
minInterval: 1
},
],
};
PieChart.vue文件代码:
<template>
<div :id="elId" style="height:100%,width:100%" />
</template>
<script>
import echarts from "echarts";
import { merge, debounce } from "lodash";
// 引入方法生成唯一uuid做为唯一标识符
import { uuid } from "@/utils/common";
// 引入公共样式
import baseOption from "./baseOption"
export default {
data() {
return {
elId: "",
vOption: {
tooltip: {
show:true,
trigger:'item',
formatter: "{b} : {c} ({d}%)",
},
xAxis: [{ show: false }],
yAxis: [{ show: false }],
series: [
{
type: "pie", // 饼图
radius: ["35%", "55%"],
center: ["50%", "45%"],
label: {
formatter: "{b}:{d}%",
fontSize: 11,
},
labelLine: {
lineStyle: {
color: "#8B96A6",
},
},
},
],
},
};
},
props: {
optionData: Object,
},
computed: {
// 合并配置对象
option() {
return merge({}, baseOption, this.vOption, this.optionData);
},
},
created() {
this.elId = uuid();
},
mounted() {
// 初始化
this.$nextTick(() => {
this.initChart();
});
},
beforeDestroy() {
if (!this.chart) {
return;
}
this.chart.dispose();
this.chart = null;
},
watch: {
optionData: {
deep: true,
handler: function() {
this.$nextTick(() => {
this.initChart();
});
},
},
},
methods: {
// 绘图
initChart() {
if(!document.getElementById(this.elId)) return
this.chart = echarts.init(document.getElementById(this.elId));
this.chart.setOption(this.option);
const that = this;
window.addEventListener(
"resize",
debounce(() => { // 引入debounce,防止频繁更改浏览页尺寸出现页面抖动
if (that.chart) {
that.chart.resize();
}
}, 100)
);
},
},
};
</script>
此时好看的图表就出现啦。