什么是echarts
使用步骤
引入echarts
npm i echarts --save-dev
在main.js中引入并注册为全局变量或者也可以只在页面中引用
// main.js
import echarts from 'echarts'
Vue.prototype.$echarts=echarts
vue页面
切记一定要设置高宽,我这里用百分比
<div id="pie_chart" style="width:100%;height:95%;"></div>
方法体
methods: {
initChart() {
//这句申明建议写到外面去
this.chart = this.$echarts.init(document.getElementById("pie_chart"), "macarons" )
this.chart.setOption({
title: {
text: "51",
x: "center",
y: "center",
textStyle: {
fontWeight: "bolder",
align: "center",
fontSize: 18
}
},
tooltip: {
trigger: "item",
formatter: "{a} <br/>{b}: {c} ({d}%)"
},
series: [
{
color: ["green", "yellow", "red", "#bbb"],
animationDuration: 4000,
name: "运行状况",
type: "pie",
radius: ["50%", "60%"],
avoidLabelOverlap: false,
label: {
normal: {
show: false,
position: "left"
}
},
labelLine: {
normal: {
show: false
}
},
data: [
{ value: 6, name: "正常" },
{ value: 0, name: "保护" },
{ value: 1, name: "故障" },
{ value: 44, name: "脱机" }
]
}
]
});
}
}
一定要在mounted调用 才能自适应 关闭页面后还要销毁监听
mounted() {
//检测 图标自适应
this.initChart();
this.__resizeHandler = debounce(() => {
if (this.chart) {
this.chart.resize();
}
}, 100);
window.addEventListener("resize", this.__resizeHandler);
},
beforeDestroy() {
//销毁检测
if (!this.chart) {
return;
}
window.removeEventListener("resize", this.__resizeHandler);
this.chart.dispose();
this.chart = null;
}
防抖
debounce方法(防抖术) 可以放到 公共工具包里 即utils 下面
export function debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result
const later = function() {
// 据上一次触发时间间隔
const last = +new Date() - timestamp
// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last)
} else {
timeout = null
// 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
if (!immediate) {
result = func.apply(context, args)
if (!timeout) context = args = null
}
}
}