Skip to content
← Back to rules

vue/no-arrow-functions-in-watch 正确性

An auto-fix is available for this rule.

作用

此规则不允许在定义 watcher 时使用箭头函数。

为什么这不好?

箭头函数会以词法方式绑定 this,这意味着它们无法访问 Vue 组件实例。 在 Vue 的 watcher 中,你通常需要访问 this 来与组件数据、方法或其他属性交互。 使用普通函数或方法简写可以确保 this 正确绑定。

示例

此规则的错误代码示例:

vue
<script>
export default {
  watch: {
    foo: () => {},
    bar: {
      handler: () => {},
    },
    baz: [
      (val) => {},
      {
        handler: () => {},
      },
    ],
  },
};
</script>

此规则的正确代码示例:

vue
<script>
export default {
  watch: {
    foo() {},
    bar: function () {},
    baz: {
      handler: function () {},
    },
  },
};
</script>

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "plugins": ["vue"],
  "rules": {
    "vue/no-arrow-functions-in-watch": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["vue"],
  rules: {
    "vue/no-arrow-functions-in-watch": "error",
  },
});
bash
oxlint --deny vue/no-arrow-functions-in-watch --vue-plugin

版本

此规则是在 v1.39.0 中添加的。

参考资料