我正在尝试使用SVG在Vue中实现拖放功能,我可以点击一个形状,它随着鼠标一起移动;但是,我无法弄清楚如何取消选择形状,以便将其放置在我发出双击事件的坐标上。这是我的Vue实例:
new Vue ({
el: '#meow',
data: {
x: '',
y: '',
rects: [
{x: 100, y: 100, width: 150, height: 150, fill: 'black'}
]
},
methods: {
moveHandler () {
this.$refs.rct[0].setAttribute('transform', `translate(${this.x-100}, ${this.y-100})`)
},
selectRect (e, idx) {
let temp = this.$refs.rct[idx]
this.$refs.wb.addEventListener('mousemove', this.moveHandler)
this.$refs.wb.addEventListener('dblclick', e => {
temp.removeAttribute('transform') // should I remove the transform attribute?
})
},
getMousePositionOnCanvas (e) {
var mousePos = this.getCoordinates(this.$refs.wb, e);
this.x = mousePos.x
this.y = mousePos.y
},
getCoordinates (canvas, evt) {
const rect = canvas.getBoundingClientRect()
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
}
}
}
})
对于工作演示:请参阅https://codepen.io/p-adams/pen/gGwEQQ?editors=1010正如您所看到的,如果我双击要放置形状的位置,则形状仍会随着鼠标移动。我在这里做错了什么?
答案 0 :(得分:2)
所以你非常接近。您的对象被双击,但鼠标移动时事件仍然存在,因此它会再次调用该函数来拖动它。您需要做的是删除该事件。
以下是您的代码段和代码笔。
selectRect (e, idx) {
let temp = this.$refs.rct[idx]
this.$refs.wb.addEventListener('mousemove', this.moveHandler)
this.$refs.wb.addEventListener('dblclick', e => {
this.$refs.wb.removeEventListener('mousemove', this.moveHandler)
})
},