1 環境: vue-cli(2.0)+ vue-echarts (git地址:https://github.com/ecomfe/vue-echarts)
2 場景:最近項目用echarts來展示圖標,其中有一個需求,需要拖動手柄,等松開手柄時,要根據手柄所在的位置(獲取手柄在的x軸信息),重新發送請求,來渲染數據。
echarts的手柄實例地址:http://echarts.baidu.com/examples/editor.html?c=line-tooltip-touch
3圖:
4遇到的bug:
4.1 手柄上的label信息,有時會刷新不出來。即上圖中的2016-10-07消失。
4.2 echarts的點擊事件對折線圖並不友好,必須點在折線圖的點坐標上才會觸發事件。so,要實現點擊圖中任意位置來即可實現觸發自己的事件。
4.3 echarts提供了可以拖動的手柄,但是並沒有松開手柄后觸發的事,這個沒有滿足我們產品的需求。當然有可能是我沒有找到,若有請告知,謝謝。
5解決以上的bug:
頁面的展示如下:
<template>
<div>
<div id='line' @touchend='touchs' @mouseup='touchs'>
<v-chart auto-resize class='zhexian' :options='lineOption' :initOptions='initOptions' ref='line' />
</div>
</div>
</template>
<script>
//初始化折線的數據 import lineoption from '@/assets/js/handleline.js' export default{ data(){ return{ lineOption:lineoption, initOptions:{ renderer: 'svg' || 'canvas' }, date:'',//發送Ajax時所需的參數 reFlag:'',//避免重復發送請求時的中間變量 } }, } </script>
拖動手柄時,會實時觸發formater,
解決第一個bug ,label有時會消失,因為我以后的代碼會用到formatter,第一次要用formater ,我是這樣寫的,
this.lineOption.xAxis.axisPoint.label.formatter=function(param){
//param是X軸的信息
2 let value = _this.$echart.format.formatTime('yyyy-MM-dd', params.value);
3 _this.date =value;
4 console.log('實時獲取的X軸的事件'+_this.date)
5 return value;
6},
,axisPoint對象的其他數據寫在了handleline.js中,解決方案就是把axisPoint的其他數據也重新setOption了,
mounted(){
2 //
3 let _this = this;
4 this.lineOption.xAxis.axisPointer={
5 value: '2016-10-7',
6 snap: true,
7 lineStyle: {
8 color: '#004E52',
9 opacity: 0.5,
10 width: 2
11 },
12 label: {
13 show: true,
14 formatter: function (params) {
15 let value = _this.$echart.format.formatTime('yyyy-MM-dd', params.value);
16 _this.date =value;
17 console.log('實時獲取的X軸的事件'+_this.date)
18 return value;
19 },
20 backgroundColor: '#004E52'
21 },
22 handle: {
23 show: true,
24 color: '#004E52'
25 }
26 }
27 },
解決第三個bug,結合了formatter 和 vue的touchend事件,單獨的formatter並沒有用,因為手指離開時,formatter的param數據會獲取多個,也有可能會是多個重復的數據。效果並不好。so結合了touchend事件,手指離開時獲取最終的date.
1 methods:{ 2 touchs(){ 3 //手指離開手柄事件,因為手柄滑動時,就會觸發formatter,這時,this.date 就會發生改變。當你手指觸發其他的地方時 4 //並不會改變this.date的值,so。為了避免手指離開時重復發送請求,需要一個中間變量。只有兩個值不相等才會去做自己想做的事。 5 if (this.reFlag == this.date) { 6 return 7 } 8 this.reFlag = this.date 9 //重新發送請求,渲染數據,這時已經或得了X軸的時間。 10 console.log(this.date) 11 // this.getPieData() 12 }, 13 }
解決第二個bug ,這是從網上找到的。實現點擊折線圖的任意地方獲取x軸的信息,發送請求。同時,要讓lineOption中的tooltip:{triggerOn:'click'},否則點擊無效。
1 sendTime() { 2 //寫在mounted中調用 3 var chart = this.$echart.init(this.$refs.line.$el) 4 chart.getZr().on('click', params => { 5 var pointInPixel = [params.offsetX, params.offsetY] 6 if (chart.containPixel('grid', pointInPixel)) { 7 let xIndex = chart.convertFromPixel({ seriesIndex: 0 }, [ 8 params.offsetX, 9 params.offsetY 10 ])[0]; 11 let a =this.$echart.format.formatTime('yyyy-MM-dd', xIndex); 12 /*事件處理代碼書寫位置*/ 13 // xIndex是個重要信息,用的時候最好打印看下具體的內容再用 14 console.log(xIndex); 15 // this.date = this.linedata[xIndex + 1][0]; 16 // 手指點擊后,讓這兩個值相等,避免觸發touchend事件, 17 this.reFlag = this.date=a; 18 //重新發送請求 19 //this.getPieData() 20 } 21 }) 22 },