思路:在配置legend里面设置一个selected,名字和series里面的name对应,name名字是必须的,legend里面的data是可配置或不配置都可以,否则legend无效,不显示,通过true和false控制显示或不显示。配置本身的legend设置不显示。通过自己写的checkbox,可自定义样式,来控制legend
如下:
data(){
return:{
//折线图例
theChart:null,
//折线图配置项
option : {
legend: {
show:false,//是否显示图例,如果要自定样式,则false
data:['line1','line2'],//series的name,也可不配置
selected:{
line1:false,//可设置变量控制check1
line2:true,//可设置变量控制check2 }
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
name: 'line1',//名字需要和legend对应得上
data: [80, 32, 91, 93, 129, 130, 120],
type: 'line',
smooth: true
} ,
{
name: 'line2',
data: [24, 32, 41, 61, 21, 31, 53],
type: 'line',
smooth: true
}
]
}
}
}
methods:{
changeLegend(params){
//初始化图例配置项,
let that=this;
let theOption=that.option;
//更新图例配置,或是改变check1,check2的变量,或是自定义组件绑定theOption.legend.selected.line1
if(params=='line1'){
theOption.legend.selected.line1=!theOption.legend.selected.line1
}
if(params=='line2'){
theOption.legend.selected.line2=!theOption..legend.selected.line2
}
//绑定配置项,第二个参数true是为了清除series切换时上次数据的缓存
this.theChart.setOption(theOption,true);
this.theChart.resize();//更新页面数据
},
}