vue项目中如何使用echarts
一、在项目终端安装echarts
npm install echarts --save
//若后续出现以下init报错,需卸载当前echarts版本
//Error in mounted hook: "TypeError: Cannot read properties of undefind (reading 'init')"
npm uninstall echarts --save//卸载echarts
npm install echarts@4.7.0 --save//安装4.7.0版本即可解决
二、在main.js中全局引入,即可在任一组件中使用this.$echarts
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
三、创建一个dom元素,并赋予其高度、宽度、id等
<div>
<div id="myCharts" ref="myCharts" style="width:500px;height:500px"></div>
</div>
四、创建一个初始化函数(以折线图为例)
initCharts() {
//使用init初始化
const myCharts = this.$echarts.init(this.$refs.myCharts);
let options = {
title: {
//图表顶部的主标题
text: "本周金额变化",
// 主标题样式
textStyle: {
color: "#000",
fontSize: 28, // 务必记住设置文字大小只能是数字
fontWeight: "normal",
},
//标题离容器左侧的距离,center为居中
left: "center",
//标题离容器顶部的距离
top: "50",
//图表副标题
subtext: "变化数额",
//副标题样式
subtextStyle: {
color: "#000",
fontSize: 16,
fontWeight: "lighter",
}, // 副标题样式
},
tooltip: {
//鼠标悬浮框的提示文字
trigger: "axis",
},
grid: {
//图标离容器的距离
y: 130,
},
legend: {
data: ["金额"],
},
xAxis: [
{
//x轴坐标数据
type: "category",
boundaryGap: false,
data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
show: false, //隐藏x轴
},
],
yAxis: [
{
//y轴坐标数据
type: "value",
axisLabel: {
formatter: "{value}",
},
show: false, //隐藏y轴
},
],
series: [
//驱动图表生成的数据内容数组,几条折现,数组中就会有几个对应对象,来表示对应的折线
{
name: "金额",
type: "line", //pie->饼状图 line->折线图 bar->柱状图
data: [45, 30, 50, 40, 45, 30, 20],
//圆滑折线
smooth: true,
//取消折点圆圈
symbol: "none",
//修改线条颜色
lineStyle: {
color: "rgb(22, 91, 250)",
},
// 辐射区域填充样式
areaStyle: {
color: {
type: "linear",
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{
offset: 0,
color: "rgba(58,132,255, 0.5)", // 0% 处的颜色
},
{
offset: 1,
color: "rgba(58,132,255, 0.3)", // 100% 处的颜色
},
],
global: false, // 缺省为 false
},
},
},
],
};
myCharts.setOption(options);
},
按需使用以及更改属性,上述代码可供参考
五、在mounted钩子里调用initChart函数
mounted() {
this.initCharts();
},