【问题标题】:Vue class component AddEventListener and RemoveEventListener usageVue类组件AddEventListener和RemoveEventListener用法
【发布时间】:2020-05-23 07:45:46
【问题描述】:

我想使用mousedownmousemovemouseup 事件来实现可拖动的线。

在我的第一次尝试中,我尝试使用箭头函数类属性: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())。由于箭头函数没有thisthis 将被视为任何其他变量,并通过父作用域进行词法查找直到找到,通常会导致诸如 Uncaught TypeError: Cannot read property of undefinedUncaught TypeError: this.myMethod is not a function 之类的错误。

在我的第二次尝试中,我尝试使用标准类方法: https://codesandbox.io/s/example-2-t7beu?fontsize=14&hidenavigation=1&theme=dark

它可以工作,除了 Test.vue 中的绑定函数 onMouseMoveonMouseUp 是匿名的,我无法使用 removeEventListener 解除绑定。

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

【问题讨论】:

    标签: vue.js vuejs2 addeventlistener vue-class-components removeeventlistener


    【解决方案1】:

    我过度设计了我的代码。 无需使用arrow-functions-class-properties,也无需使用method.bind(this) 定义上下文。以下代码应该可以工作:

    import { Vue, Component } from "vue-property-decorator";
    
    @Component
    export default class Test extends Vue {
      position = 0;
    
      onMouseMove(e) {
        let position = this.position;
        position += e.movementY;
        this.position = position;
        console.log("onMouseMove", this.position);
      }
    
      onMouseUp() {
        console.log("onMouseUp", this.position);
        document.removeEventListener("mousemove", this.onMouseMove);
        document.removeEventListener("mouseup", this.onMouseUp);
      }
    
      onMouseDown() {
        console.log("onMouseDown", this.position);
        document.addEventListener("mousemove", this.onMouseMove);
        document.addEventListener("mouseup", this.onMouseUp);
      }
    }
    
    

    工作示例:https://codesandbox.io/s/example-2-t7beu?fontsize=14&hidenavigation=1&theme=dark

    【讨论】:

      猜你喜欢
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2022-11-02
      相关资源
      最近更新 更多