生鲜电商网站建设与管理关键词优化一般收费价格
-
需求:写图表的时候想把框选工具和页面其他操作按钮放在一起统一样式,所以不能使用echart自带的按钮来实现了,需要通过点击自己写的按钮来实现,框选图表区域后,获取当前区域x轴时间范围,然后把这个时间范围当作入参调取后端接口获取这个时间段的数据渲染到图表上
-
核心:看开发文档,发现echart的brush的自己的工具也是通过调取
takeGlobalCursor
方法来实现开启或者关闭框选状态的 -
逻辑:点击自己写的按钮开启框选状态,再给echart增加个监听
brushSelected
事件的函数,来监听框选状态的变化,从而计算出x轴此时的时间范围获取入参的值 -
代码环境:vue3、ts、echart^5.4.2
-
图片
-
代码
<div class="icon-w" @click="openBrush" ></div> <div class="z-echartbox" style="height:50vh;width:100%"><div class="z-echart" style="height:50vh;width:100%" ref="online"></div> </div>// js import * as echarts from 'echarts'; import { EChartsOption } from 'echarts';const online = ref(); // 点击自写按钮,启动brush框选状态 const openBrush = ()=>{// console.log('开启手动框选')selectStatus.value = trueglobal[name].dispatchAction({ // global[name] ==online.value,就是你创建的echart名字type: 'takeGlobalCursor',// 如果想变为“可刷选状态”,必须设置。不设置则会关闭“可刷选状态”。key: 'brush',brushOption: {// 参见 brush 组件的 brushType。如果设置为 false 则关闭“可刷选状态”。brushType: 'rect', // 关键,值要写对不然启动不了// 参见 brush 组件的 brushMode。如果不设置,则取 brush 组件的 brushMode 设置。// brushMode: 'multiple'}});}// 初始化表格,在初始化的时候监听表格缩放函数 const initPieChart = (target,option,name)=>{ // ref值 ;表格的option设置值;自己起的表格别名其实等于global[name] global[name] = <any>echarts.init(target.value, charts.theme);(<any>global[name]).setOption(option);// 监听缩放global[name].on('brushSelected', (params) => { // global[name]===online.value,用这个替代也行const brushComponent = params.batch[0];if (brushComponent?.areas?.length) {// console.log('开始框选')const [startIndex, endIndex] = brushComponent.areas[0].coordRange;// console.log('echartData.value',echartData.value)// console.log('echartData.value[Math.floor(startIndex)]',(echartData.value)[Math.floor(startIndex)])// 将索引转换为 xAxis.data 中的分类值// 这里需要注意,框选的返回的params额属性超级多复杂,找到自己需要的比如我查看属性发现只需要使用brushComponent.areas[0].coordRange的startIndex值就行了不需要endIndexconst startTime = echartData.value[Math.floor(startIndex[0])]; //const endTime = echartData.value[Math.floor(startIndex[1])];// 发送后端请求 searchObj.value.begin = startTime // 页面的时间选择器值,也需要同步显示框选的时间范围searchObj.value.end = endTime// 页面的时间选择器值,也需要同步显示框选的时间范围onSearch()}});}// 切换页面后删除监听事件,不要在意我使用的组件周期,我是使用了keep缓存组件所以通过这个周期来清空操作 onDeactivated (()=> {if (global[name]) {global[name].dispose();global[name].off('brushSelected'); // 移除事件监听}})// 一些图标设置option = {brush: {xAxisIndex: 0, // 绑定到第一个x轴brushType: 'rect', // 矩形框选throttleType: 'debounce',throttleDelay: 300,tooltip: false},toolbox: {feature: {brush: { type: ['rect'] ,show: false,}, // 不显示图标按钮},left:'center',top:'2%',// height:'40px',},}