首页 > 解决方案 > 无法将事件绑定到对象方法

问题描述

我有一个 vue 单文件组件,它有一个自定义类实例作为属性:现在我想将一个事件绑定到这个类实例的一个方法,但是我遇到了问题,我的代码文件有一个简化版本

VueJS 单文件组件

    <template>
        <div @click="class_prop.method"></div>
    </template>

    export default {
      data() {
        return {
            class_prop: new CustomClass(),
        };
      },
    }

自定义类

    class CustomClass {
        constructor(){
            this.prop = 'default_value';
        }

        method(){
            this.prop = 'new_value';
            console.log(this.prop);
        }
    }

错误

单击页面元素时,我收到此错误:

[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'prop' of null"

但是当我尝试从浏览器控制台调用自定义类方法时(我正在使用带有 Vue Devtools 扩展的 Chrome)我没有收到错误,它可以正常工作:

$vm0.class_prop.method()

由于我的代码有两种不同的行为,我无法判断是我的类错误、vue 单文件组件还是其他原因。

标签: vue.jseventsmethodsbinding

解决方案


你看到的不是 Vue 的错,它只是普通的 JavaScript。

这是来自优秀 JS 学习资源的引用

未绑定的后果this

如果您来自另一种编程语言,那么您可能已经习惯了“绑定 this”的想法,其中定义在对象中的方法总是this引用该对象。在 JavaScriptthis中是“免费的”,它的值是在调用时评估的,它不依赖于声明方法的位置,而是依赖于“点之前”的对象。

这是上述段落后果的非常简单的示例(以及为什么您的代码不起作用):

class CustomClass {
  constructor() {
    this.prop = 'default_value';
  }

  method() {
    this.prop = 'new_value';
    console.log(this.prop);
  }
}

let instance = new CustomClass()

instance.method() // this works OK

let f = instance.method

f() // this does not! f is "unbound" ....have no "this"


推荐阅读