<template>
<div ref="echart" class="echart"></div>
</template>
<script>
import echarts from "echarts";
import "echarts/theme/shine";
export default {
data() {
// 直接写在return 里会不显示 tooltip
this.chart = null;
return {};
},
mounted() {
this.$nextTick(() => {
this.initChart();
});
},
beforeUnmount() {
if (!this.chart) {
return;
}
this.chart.dispose();
this.chart = null;
},
methods: {
// 图表初始化
initChart() {
this.chart = echarts.init(this.$refs.echart, "shine");
this.setOptions();
},
// 设置图表
setOptions() {
this.chart.setOption({
title: {
text: "图表标题",
},
// 提示框组件 (全局)
tooltip: {
// 触发类型 : item 数据项图形触发(主要在散点图,饼图等无类目轴的图表中使用); axis 坐标轴触发(主要在柱状图,折线图等会使用类目轴的图表中使用); none 什么都不触发
trigger: "axis",
axisPointer: {
type: "cross",
},
show: true,
},
// 图例组件
legend: {
// 数据组 数组项通常为一个字符串,每一项代表一个系列的 name 对应 series 里的 name
data: ["Email", "Union Ads", "Video Ads", "Direct", "Search Engine"],
right: 50,
},
// 直角坐标系内绘图网格,单个 grid 内最多可以放置上下两个 X 轴,左右两个 Y 轴。
grid: {
// 距离
left: "3%",
right: "4%",
bottom: "3%",
// grid 区域是否包含坐标轴的刻度标签
containLabel: true,
},
// 工具栏
toolbox: {
feature: {
// 保存为图片
saveAsImage: {},
},
},
// 直角坐标系 grid 中的 x 轴,一般情况下单个 grid 组件最多只能放上下两个 x 轴,多于两个 x 轴需要通过配置 offset 属性防止同个位置多个 x 轴的重叠。
xAxis: {
/* 坐标轴类型
value:数值轴,适用于连续数据;
category:类目轴,适用于离散的类目数据。为该类型时类目数据可自动从 series.data 或 dataset.source 中取,或者可通过 xAxis.data 设置类目数据;
time: 时间轴,适用于连续的时序数据,与数值轴相比时间轴带有时间的格式化,在刻度计算上也有所不同,例如会根据跨度的范围来决定使用月,星期,日还是小时范围的刻度。
log: 对数轴。适用于对数数据
*/
type: "category",
// 坐标轴两边留白策略,类目轴和非类目轴的设置和表现不一样。可以配置为 true 和 false。默认为 true,这时候刻度只是作为分隔线,标签和数据点都会在两个刻度之间的带(band)中间
boundaryGap: false,
// 类目数据,在类目轴(type: 'category')中有效。
data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
},
yAxis: {
// 同 xAxis
type: "value",
},
series: [
{
name: "Email",
type: "line",
data: [120, 132, 101, 134, 90, 230, 210],
// areaStyle: {},
smooth: true // 平滑折线
},
{
name: "Union Ads",
type: "line",
data: [220, 182, 191, 234, 290, 330, 310],
// areaStyle: {},
smooth: true
},
{
name: "Video Ads",
type: "line",
data: [150, 232, 201, 154, 190, 330, 410],
// areaStyle: {},
smooth: true
},
{
name: "Direct",
type: "line",
data: [320, 332, 301, 334, 390, 330, 320],
// areaStyle: {},
smooth: true
},
{
name: "Search Engine",
type: "line",
data: [820, 932, 901, 934, 1290, 1330, 1320],
// areaStyle: {},
smooth: true
},
],
});
},
},
};
</script>
<style lang="less" scoped>
.echart {
height: 400px;
}
</style>
如何在vue3中使用echarts