Skip to content
← Back to rules

vue/define-emits-declaration Style

🚧 An auto-fix is planned for this rule, but not implemented at this time.

作用

此规则强制规范 defineEmits 的类型声明风格,你应当使用 type-based、严格的 type-literal(引入于 Vue 3.3),或 runtime 声明。 此规则仅在 setup script 和 lang="ts" 中生效。

为什么这不好?

不一致的代码风格会让人困惑,并使代码更难阅读。

示例

以下是此规则的错误代码示例:

vue
// "vue/define-emits-declaration": ["error", "type-based"]
<script setup lang="ts">
const emit = defineEmits(["change", "update"]);
const emit2 = defineEmits({
  change: (id) => typeof id === "number",
  update: (value) => typeof value === "string",
});
</script>

// "vue/define-emits-declaration": ["error", "type-literal"]
<script setup lang="ts">
const emit = defineEmits<{
  (e: "change", id: number): void;
  (e: "update", value: string): void;
}>();
</script>

// "vue/define-emits-declaration": ["error", "runtime"]
<script setup lang="ts">
const emit = defineEmits<{
  (e: "change", id: number): void;
  (e: "update", value: string): void;
}>();
</script>

以下是此规则的正确代码示例:

vue
// "vue/define-emits-declaration": ["error", "type-based"]
<script setup lang="ts">
const emit = defineEmits<{
  (e: "change", id: number): void;
  (e: "update", value: string): void;
}>();
const emit2 = defineEmits<{
  change: [id: number];
  update: [value: string];
}>();
</script>

// "vue/define-emits-declaration": ["error", "type-literal"]
<script setup lang="ts">
const emit = defineEmits<{
  change: [id: number];
  update: [value: string];
}>();
</script>

// "vue/define-emits-declaration": ["error", "runtime"]
<script setup lang="ts">
const emit = defineEmits<{
  (e: "change", id: number): void;
  (e: "update", value: string): void;
}>();
const emit2 = defineEmits({
  change: (id) => typeof id === "number",
  update: (value) => typeof value === "string",
});
</script>

配置

此规则接受以下字符串值之一:

"type-based"

强制使用命名的 TypeScript 类型或接口作为 defineEmits 的参数,例如 defineEmits<MyEmits>()

"type-literal"

强制使用内联类型字面量作为 defineEmits 的参数,例如 defineEmits<{ (event: string): void }>()

"runtime"

强制使用运行时声明,即通过数组或对象声明 emits,例如 defineEmits(['event1', 'event2'])

如何使用

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

json
{
  "plugins": ["vue"],
  "rules": {
    "vue/define-emits-declaration": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["vue"],
  rules: {
    "vue/define-emits-declaration": "error",
  },
});
bash
oxlint --deny vue/define-emits-declaration --vue-plugin

版本

此规则于 v1.15.0 中添加。

参考资料