vue项目,要求echarts折线图展示的曲线,也就是legend很多的时候,需要以复选框的形式展示,
echarts社区里并没有发现类似的案例,研究了文档后发现,可以通过修改配置,然后再次调用setOption方法实现。
我的做法是添加一组checkbox,点击按钮的时候,触发事件重新画图。代码不复杂,贴在下面。
<template>
<div>
<h1>echarts</h1>
<el-checkbox-group v-model="checkList" @change="checked">
<el-checkbox label="邮件营销"></el-checkbox>
<el-checkbox label="联盟广告"></el-checkbox>
<el-checkbox label="视频广告"></el-checkbox>
<el-checkbox label="直接访问"></el-checkbox>
<el-checkbox label="搜索引擎"></el-checkbox>
</el-checkbox-group>
<div class="content_echarts" ref="foldLine"></div>
</div>
</template>
<script>
import * as echarts from "echarts";
export default {
data() {
return {
checkList: ["邮件营销", "联盟广告", "视频广告", "直接访问", "搜索引擎"],
};
},
watch: {},
computed: {},
created() {},
mounted() {
this.initChart();
},
methods: {
checked(i) {
let selectArr = this.chartInstance.getOption().legend[0].data; //legend所有值
let selected = {}; // 创建一个空对象来存储选中状态
for (let item of selectArr) {
selected[item] = this.checkList.includes(item); // 判断selectArr数组中是否包含当前元素,如果包含则为true,否则为false
}
let option = {
legend: {
selected, // 将选中状态对象赋值给legend的selected属性
},
};
//更新echarts图表
this.chartInstance.setOption(option);
},
//初始化实例方法
initChart() {
this.chartInstance = echarts.init(this.$refs.foldLine);
const initOption = {
tooltip: {
trigger: "axis",
},
grid: {
//边框
//x:100,
x2: 100,
//y:50
//height:350
},
legend: {
show: false,
data: ["邮件营销", "联盟广告", "视频广告", "直接访问", "搜索引擎"],
orient: "vertical",
right: 0,
top: 100,
bottom: 20,
//selected:{'邮件营销':true,'联盟广告':false,'视频广告':true,'直接访问':true,'搜索引擎':true}
},
calculable: true,
xAxis: [
{
type: "category",
boundaryGap: false,
data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
},
],
yAxis: [
{
type: "value",
},
],
series: [
{
name: "邮件营销",
type: "line",
stack: "总量",
data: [120, 132, 101, 134, 90, 230, 210],
selected: false,
},
{
name: "联盟广告",
type: "line",
stack: "总量",
data: [220, 182, 191, 234, 290, 330, 310],
},
{
name: "视频广告",
type: "line",
stack: "总量",
data: [150, 232, 201, 154, 190, 330, 410],
},
{
name: "直接访问",
type: "line",
stack: "总量",
data: [320, 332, 301, 334, 390, 330, 320],
},
{
name: "搜索引擎",
type: "line",
stack: "总量",
data: [820, 932, 901, 934, 1290, 1330, 1320],
},
],
};
this.chartInstance.setOption(initOption);
},
},
};
</script>
<style lang="scss" scoped>
.content_echarts {
width: 800px;
height: 500px;
}
</style>