存储坐标信息的数据结构 在 Vue 中,可以使用一个数组来维护每个项目的坐标信息,如下所示:
items: [
{ name: 'Project A', x: 0, y: 0, width: 4 },
{ name: 'Project B', x: 4, y: 0, width: 2 },
{ name: 'Project C', x: 6, y: 0, width: 3 },
// ...
]
其中 x 和 y 表示项目的起始位置,width 表示项目的宽度(以格子数为单位)。 2.拖拽事件处理函数 为了实现拖拽功能,我们需要为每个项目绑定相应的拖拽事件处理函数。在 Vue 中,可以使用 v-on:mousemove、v-on:mousedown 和 v-on:mouseup 等指令来定义这些事件处理函数。
首先,当用户在项目上按下鼠标左键时,需要记录当前鼠标的位置和项目的原始坐标:
onMouseDown(event, item) {
this.dragging = true
this.draggedItem = item
const rect = event.currentTarget.getBoundingClientRect()
this.mouseStartX = event.clientX
this.itemStartX = item.x
}
接着,在鼠标移动时,需要计算出项目应该移动到的位置并更新其坐标信息:
onMouseMove(event) {
if (this.dragging) {
const deltaX = event.clientX - this.mouseStartX
const newX = this.itemStartX + this.pxToGrid(deltaX)
this.draggedItem.x = Math.max(0, newX)
}
}
其中,pxToGrid 函数用于将像素值转换成格子数,可以根据实际需要来设置。
最后,在鼠标释放时,需要将 dragging 置为 false,表示拖拽已结束:
onMouseUp() {
this.dragging = false
this.draggedItem = null
this.mouseStartX = null
this.itemStartX = null
}
至此,左右拖动的功能已经实现了。
3.上下拖动的处理 要实现上下拖动,需要先为每个项目添加一个高度属性 height。另外,还需要将整个甘特图的高度设为一个常量,比如 300px。
然后,在拖拽事件处理函数中,需要根据当前鼠标的位置来计算出项目应该移动到的位置,并更新其 y 和 height 属性:
onMouseDown(event, item) {
// ...
const rect = event.currentTarget.getBoundingClientRect()
this.mouseStartY = event.clientY
this.itemStartY = item.y
this.itemStartHeight = item.height
}
onMouseMove(event) {
if (this.dragging) {
const deltaY = event.clientY - this.mouseStartY
const newY = this.itemStartY + this.pxToGrid(deltaY)
const newHeight = this.itemStartHeight - this.pxToGrid(deltaY)
const maxTop = this.containerHeight - newHeight
this.draggedItem.y = Math.min(Math.max(0, newY), maxTop)
this.draggedItem.height = newHeight
}
}
onMouseUp() {
// ...
this.mouseStartY = null
this.itemStartY = null
this.itemStartHeight = null
}
其中,containerHeight 表示甘特图的高度(即容器的高度),可以在页面加载时获取。注意,需要限制项目的 y 坐标在 [0, maxTop] 的范围之内,以避免项目移出甘特图的可见区域。
推荐文章: