一、安装 echarts
echarts官网:https://echarts.apache.org/zh/index.html
npm install echarts --save
二、引入 echarts
要在 main.js 中引入!!!
// 引入echarts
import echarts from "echarts";
Vue.prototype.$echarts = echarts;
三、在 vue 中使用
1.在需要插入 echarts 的地方 设置一个 div 盒子
2.给 div 设置 ref 属性以及 width 和 height
<template>
<div class="container">
<div ref="chart" style="width:xxx; height:xxx"></div>
</div>
</template>
四、给 echarts 进行配置,实现简单效果
1.第一种方式
mounted() {
this.getEchartData();
},
methods: {
getEchartData() {
const chart = this.$refs.chart;
if (chart) {
const myChart = this.$echarts.init(chart);
const option = {
// category 表示类目轴
xAxis: {
type: "category",
data: [ "10:00","10:30", "11:00", "11:30", "12:00", "12:30", "13:00", "13:30" ],
},
// value 表示数值轴,数据写在 series 中
yAxis: { type: "value" },
series: [
{
name: "总访问量",
type: "line",
data: [43, 83, 86, 72, 82, 52, 72, 72],
},
{
name: "总会话量",
type: "line",
data: [85, 73, 65, 53, 49, 74, 53, 53],
},
{
name: "有效会话量",
type: "line",
data: [68, 60, 72, 68, 70, 65, 68, 74],
},
],
};
myChart.setOption(option);
window.addEventListener("resize", function () {
myChart.resize();
});
}
this.$on("hook:destroyed", () => {
window.removeEventListener("resize", function () {
myChart.resize();
});
});
},
},
1.第二种方式
mounted() {
this.getEchartData();
},
methods: {
getEchartData() {
const chart = this.$refs.chart;
if (chart) {
const myChart = this.$echarts.init(chart);
const option = {
dataset: {
source: [
["10:00", 43, 85, 68],
["10:30", 83, 73, 60],
["11:00", 86, 65, 72],
["11:30", 72, 53, 68],
["12:00", 82, 49, 70],
["12:30", 52, 74, 65],
["13:00", 72, 53, 68],
["13:30", 72, 53, 74],
],
},
xAxis: { type: "category" },
yAxis: { type: "value" },
series: [
{ name: "总访问量", type: "line" },
{ name: "总会话量", type: "line" },
{ name: "有效会话量", type: "line" },
],
};
myChart.setOption(option);
window.addEventListener("resize", function () {
myChart.resize();
});
}
this.$on("hook:destroyed", () => {
window.removeEventListener("resize", function () {
myChart.resize();
});
});
},
},
五、效果展示
六、最后
如果出现报错情况,尝试一下给 echarts 降级
- 卸载当前版本:npm uninstall echarts
- 安装指定版本:npm install echarts@4.9.0
- 如果还出现报错,重新启动项目即可!!!!!