今天就跟大家聊聊有關使用Echart怎么實現折線圖手柄觸發事件,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
1 環境:
vue-cli(2.0)+ vue-echarts
2 場景:
需求,需要拖動手柄,等松開手柄時,要根據手柄所在的位置(獲取手柄在的x軸信息),重新發送請求,來渲染數據。
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軸的信息
let value = _this.$echart.format.formatTime('yyyy-MM-dd', params.value);
_this.date =value;
console.log('實時獲取的X軸的事件'+_this.date)
return value;
},,axisPoint對象的其他數據寫在了handleline.js中,解決方案就是把axisPoint的其他數據也重新setOption了,
mounted(){
//
let _this = this;
this.lineOption.xAxis.axisPointer={
value: '2016-10-7',
snap: true,
lineStyle: {
color: '#004E52',
opacity: 0.5,
width: 2
},
label: {
show: true,
formatter: function (params) {
let value = _this.$echart.format.formatTime('yyyy-MM-dd', params.value);
_this.date =value;
console.log('實時獲取的X軸的事件'+_this.date)
return value;
},
backgroundColor: '#004E52'
},
handle: {
show: true,
color: '#004E52'
}
}
},解決第三個bug,結合了formatter 和 vue的touchend事件,單獨的formatter并沒有用,因為手指離開時,formatter的param數據會獲取多個,也有可能會是多個重復的數據。效果并不好。so結合了touchend事件,手指離開時獲取最終的date.
methods:{
touchs(){
//手指離開手柄事件,因為手柄滑動時,就會觸發formatter,這時,this.date 就會發生改變。當你手指觸發其他的地方時
//并不會改變this.date的值,so。為了避免手指離開時重復發送請求,需要一個中間變量。只有兩個值不相等才會去做自己想做的事。
if (this.reFlag == this.date) {
return
}
this.reFlag = this.date
//重新發送請求,渲染數據,這時已經或得了X軸的時間。
console.log(this.date)
// this.getPieData()
},
}解決第二個bug ,這是從網上找到的。實現點擊折線圖的任意地方獲取x軸的信息,發送請求。同時,要讓lineOption中的tooltip:{triggerOn:'click'} ,否則點擊無效。
sendTime() {
//寫在mounted中調用
var chart = this.$echart.init(this.$refs.line.$el)
chart.getZr().on('click', params => {
var pointInPixel = [params.offsetX, params.offsetY]
if (chart.containPixel('grid', pointInPixel)) {
let xIndex = chart.convertFromPixel({ seriesIndex: 0 }, [
params.offsetX,
params.offsetY
])[0];
let a =this.$echart.format.formatTime('yyyy-MM-dd', xIndex);
/*事件處理代碼書寫位置*/
// xIndex是個重要信息,用的時候最好打印看下具體的內容再用
console.log(xIndex);
// this.date = this.linedata[xIndex + 1][0];
// 手指點擊后,讓這兩個值相等,避免觸發touchend事件,
this.reFlag = this.date=a;
//重新發送請求
//this.getPieData()
}
})
},看完上述內容,你們對使用Echart怎么實現折線圖手柄觸發事件有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。