【发布时间】:2020-05-23 07:45:46
【问题描述】:
我想使用mousedown、mousemove 和mouseup 事件来实现可拖动的线。
在我的第一次尝试中,我尝试使用箭头函数类属性:https://codesandbox.io/s/example-1-15psm?fontsize=14&hidenavigation=1&theme=dark
但是Test.vue 中的属性position 似乎没有反应。不确定,但我猜是因为this Vue 限制:
不要在选项属性或回调上使用箭头函数,例如
created: () => console.log(this.a)或vm.$watch('a', newValue => this.myMethod())。由于箭头函数没有this,this将被视为任何其他变量,并通过父作用域进行词法查找直到找到,通常会导致诸如 UncaughtTypeError: Cannot read property of undefined或Uncaught TypeError: this.myMethod is not a function之类的错误。
在我的第二次尝试中,我尝试使用标准类方法: https://codesandbox.io/s/example-2-t7beu?fontsize=14&hidenavigation=1&theme=dark
它可以工作,除了 Test.vue 中的绑定函数 onMouseMove 和 onMouseUp 是匿名的,我无法使用 removeEventListener 解除绑定。
那么,在 Vue 类组件中使用addEventListener 和removeEventListener 的正确方法是什么?
【问题讨论】:
标签: vue.js vuejs2 addeventlistener vue-class-components removeeventlistener