vue+echarts实现可拖动节点的折线图(⽀持拖动⽅向和上下限的设置)需求:制作⼀个折线图⽤于显⽰当前24⼩时的数据,并且可以通过拖动折现图设置数据
效果图如下:初步看和⼀般的折线图没什么区别,但是实际如图⽰,节点是可以上下拖动的
代码如下:
<template>
<div ref="dom" class="charts chart-bar"></div>
</template>
<script>
import echarts from 'echarts'
import tdTheme from '_c/charts/theme.json' // 这是我⾃⼰写的主题⽂件,可以不⽤管
import { on, off } from '@/libs/tools' // 这是其他⼀些⽅法函数,可以不管
export default {
name: 'ChartLine',
props: {
text: String,
subtext: String,
yName: String
},
data () {
return {
dom: null,
symbolSize: 5,
    // 通过拖动是可以实时改变这⾥的值的
data: [[0, 10], [1, 10], [2, 20], [3, 30], [4, 36], [5, 20], [6, 25], [7, 20], [8, 21], [9, 22],
[10, 23], [11, 25], [12, 10], [13, 11], [14, 19], [15, 20], [16, 12], [17, 13], [18, 12], [19, 9],
[20, 21], [21, 18], [22, 10], [23, 12]]
}
},
methods: {
resize () {
size()
}
},
mounted () {
this.dom = echarts.init(this.$refs.dom, 'tdTheme')
this.dom.setOption({
title: {
text: ,
subtext: this.subtext,
x: 'center'
},
grid: {
left: 50,
top: 40
setoption},
tooltip: {
trigger: 'axis'
},
xAxis: {
min: 0,
max: 23,
type: 'value',
axisLabel: {
formatter (value) {
return value + ':00' // 格式时间显⽰⽅式
}
},
axisLine: { onZero: false }
},
yAxis: {
min: 4,
max: 36,
type: 'value',
name: this.yName,
axisLine: { onZero: false }
},
series: [
{
id: 'a',
type: 'line',
smooth: true,
symbolSize: this.symbolSize, // 为了⽅便拖拽,把 symbolSize 尺⼨设⼤了。
data: this.data
}
]
})
this.dom.setOption({
graphic: echarts.util.map(this.data, (dataItem, dataIndex) => {
const that = this // 因为ondrag函数必须在回调内使⽤this.position获取实时坐标,此处必须⽤that替换this
return {
// 'circle' 表⽰这个 graphic element 的类型是圆点。
type: 'circle',
shape: {
// 圆点的半径。
r: this.symbolSize / 2
},
// ⽤ transform 的⽅式对圆点进⾏定位。position: [x, y] 表⽰将圆点平移到 [x, y] 位置。
// 这⾥使⽤了 convertToPixel 这个 API 来得到每个圆点的位置
position: vertToPixel('grid', dataItem),
// 这个属性让圆点不可见(但是不影响他响应⿏标事件)。
invisible: true,
// 这个属性让圆点可以被拖拽。
draggable: true,
// 把 z 值设得⽐较⼤,表⽰这个圆点在最上⽅,能覆盖住已有的折线图的圆点。
z: 100,
ondrag: echarts.util.curry(function (dataIndex) { // 此处必须⽤匿名函数,不能⽤箭头函数,否则拿不到拖动的坐标
let origin = vertToPixel('grid', that.data[dataIndex]) // 得到每个圆点原始位置
// let maxY = vertToPixel('grid', [40, 36]) // 最⾼温度为36摄⽒度,暂未做封装
// 超过最⾼温度36将不能拖动,写死的最低点⾼度为240,最⾼点为40
if (this.position[1] > 240) {
this.position[1] = 240
} else if (this.position[1] < 40) {
this.position[1] = 40
}
this.position[0] = origin[0] // 控制每个点位只能在y轴⽅向移动
// this.position[1] = origin[1] // 控制每个点位只能在x轴⽅向移动
// 实时获取拖动的点位信息并根据此信息重新画图
that.data[dataIndex] = vertFromPixel('grid', this.position)
that.dom.setOption({
series: [{
id: 'a',
data: that.data
}]
})
}, dataIndex)
}
})
})
on(window, 'resize', this.dom.setOption({
graphic: echarts.util.map(this.data, (item, dataIndex) => {
return {
position: vertToPixel('grid', item)
}
})
}))
},
beforeDestroy () {
off(window, 'resize', size)
}
}
</script>
总结
以上所述是⼩编给⼤家介绍的vue+echarts实现可拖动节点的折线图(⽀持拖动⽅向和上下限的设置),希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!
如果你觉得本⽂对你有帮助,欢迎转载,烦请注明出处,谢谢!