首页 > 解决方案 > 函数类型设置'this'上下文,不起作用

问题描述

我的 Vue 组件中有以下代码:

import Vue from 'vue';
import { ElForm } from 'element-ui/types/form';

type Validator = (
  this: typeof PasswordReset,
  rule: any,
  value: any,
  callback: (error?: Error) => void
) => void;

const validatePass1: Validator = (rule, value, callback) => {
  if (value && this.form.passwordConfirm) {
    (this.$refs.form as ElForm).validateField('passwordConfirm', valid => {});
  }
};
// ...

const PasswordReset = Vue.extend({
  // ...

这不像记录的那样工作。validatePass1我在func中收到类型错误:

'this' implicitly has type 'any' because it does not have a type annotation.

我不明白为什么这不起作用。

标签: typescriptvue.js

解决方案


validatePass1需要用function关键字而不是箭头函数来定义。箭头函数忽略this调用时传递的(这是您的类型注释所在),并始终使用this定义它的位置,在这种情况下是全局对象(我认为)。


推荐阅读