Vize

script/no-arrow-functions-in-watch

Proibir funções de seta como manipuladores de watch na Options API.

Severidade padrão Predefinições Correção automática Opções
error essential, happy-path, ecosystem, nuxt, opinionated Não Nenhuma

Aplicável a: Scripts JS/TS em SFCs Vue; os exemplos mostram a forma relevante de Options API ou script setup.

Incorreto

O observador value da Options API e o other.handler aninhado são funções de seta. Uma função de seta captura o this do contexto ao redor em vez de receber a instância do componente.

<script lang="ts">
export default {
  watch: {
    // `this` is not the component instance inside an arrow function.
    value: () => {
      this.doSomething()
    },
    other: {
      handler: () => {}
    }
  }
}
</script>

Correto

Ambos os manipuladores passam a ser métodos comuns, permitindo que o Vue vincule this ao componente. A opção deep: true do observador continua compatível com a forma de objeto.

<script lang="ts">
export default {
  watch: {
    value(newValue, oldValue) {
      this.doSomething()
    },
    other: {
      handler(newValue) {},
      deep: true
    }
  }
}
</script>

Configuração (Vite+)

import { defineConfig } from "@vizejs/vite-plugin/vite-plus";

export default defineConfig({}).withVue({
  linter: {
    "preset": "incremental",
    "rules": {
      "script/no-arrow-functions-in-watch": "error"
    }
  },
});

Depois, execute vp run lint.

Páginas relacionadas