Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js Vue类组件AddEventListener和RemoveEventListener的使用_Vue.js_Vuejs2_Addeventlistener_Vue Class Components_Removeeventlistener - Fatal编程技术网

Vue.js Vue类组件AddEventListener和RemoveEventListener的使用

Vue.js Vue类组件AddEventListener和RemoveEventListener的使用,vue.js,vuejs2,addeventlistener,vue-class-components,removeeventlistener,Vue.js,Vuejs2,Addeventlistener,Vue Class Components,Removeeventlistener,我想使用mousedown、mousemove和mouseup事件实现可拖动的行 在我的第一次尝试中,我尝试使用arrow函数类属性: 但是Test.vue中的属性position似乎没有反应。不确定,但我猜这是因为Vue限制: 不要在选项属性或回调上使用箭头函数,例如created:()=>console.log(this.a)或vm.$watch('a',newValue=>this.myMethod())。由于箭头函数没有this,this将被视为任何其他变量,并通过父作用域进行词汇查找,

我想使用
mousedown
mousemove
mouseup
事件实现可拖动的行

在我的第一次尝试中,我尝试使用arrow函数类属性:

但是
Test.vue
中的属性
position
似乎没有反应。不确定,但我猜这是因为Vue限制:

不要在选项属性或回调上使用箭头函数,例如
created:()=>console.log(this.a)
vm.$watch('a',newValue=>this.myMethod())
。由于箭头函数没有
this
this
将被视为任何其他变量,并通过父作用域进行词汇查找,直到找到为止,通常会导致错误,如未捕获
类型错误:无法读取未定义的
未捕获类型错误的属性:this.myMethod不是函数

在第二次尝试中,我尝试使用标准类方法:

它可以工作,除了在
Test.vue
中绑定的函数
onMouseMove
onMouseUp
是匿名的,我不能用
removeEventListener
解除绑定


那么,在Vue类组件中使用
addEventListener
removeEventListener
的正确方法是什么呢?

我的代码设计过度了。 无需使用
箭头函数类属性,也无需使用
方法.bind(this)
定义上下文。以下代码应该可以工作:

从“Vue属性装饰器”导入{Vue,组件};
@组成部分
导出默认类测试扩展Vue{
位置=0;
onMouseMove(e){
设position=this.position;
位置+=e.movementY;
这个位置=位置;
log(“onMouseMove”,this.position);
}
onMouseUp(){
log(“onMouseUp”,this.position);
document.removeEventListener(“mousemove”,this.onMouseMove);
document.removeEventListener(“mouseup”,this.onMouseUp);
}
onMouseDown(){
log(“onMouseDown”,this.position);
document.addEventListener(“mousemove”,this.onMouseMove);
document.addEventListener(“mouseup”,this.onMouseUp);
}
}
工作示例: