vue.js - 无法将事件绑定到对象方法
问题描述
我有一个 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 的错,它只是普通的 JavaScript。
未绑定的后果
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"
推荐阅读
- python - 如何在 Tkinter 的菜单项中包含计算功能?
- react-native - 使用 xstream 和 react-native-svg-charts 将流中的数据绘制成图形
- python - TypeError: 不支持的操作数类型 -: 'DatetimeArray' 和 'datetime.date'
- django - 尝试更改 django detailView 上的相关模型时出现属性错误
- android - google ml kit 重复依赖
- android-studio - AndroidStudio 说无法识别启动活动:未找到默认活动”
- javascript - WASI-libc 在写入标准输入时等待用户输入
- node.js - 全新安装 nginx 超时,但服务正在运行
- r - 网页列表中的网页抓取,R中没有明确的分隔符
- python - 复制了数据帧,但是:“无法为非唯一标签获取正确的切片:时间戳”