Skip to content
← Back to rules

vue/valid-define-props 正确性

An auto-fix is available for this rule.

它做了什么

此规则检查 defineProps 编译器宏是否有效。

当出现以下情况时,该规则会报告 defineProps 编译器宏:

  • defineProps 引用了本地声明的变量。
  • defineProps 同时具有字面量类型和参数。例如:defineProps<{ /*props*/ }>({ /*props*/ })
  • defineProps 被调用多次。
  • 既在 defineProps 又在 export default {} 中定义了属性。
  • 既未在 defineProps 也未在 export default {} 中定义属性。

为什么这是个问题?

错误使用 defineProps 可能导致运行时错误,并丢失类型安全。 虽然 Vue 仍可能编译代码,但属性可能会无声地失效或类型被错误地推断。

示例

此规则的错误代码示例:

vue
<script setup>
const def = { msg: String };
defineProps(def);
</script>
vue
<script setup lang="ts">
defineProps<{ msg?: string }>({ msg: String });
</script>
vue
<script setup>
defineProps({ msg: String });
defineProps({ count: Number });
</script>
vue
<script>
export default {
  props: { msg: String },
};
</script>
<script setup>
defineProps({ count: Number });
</script>

此规则的正确代码示例:

vue
<script setup>
defineProps({ msg: String });
</script>
vue
<script setup>
defineProps(["msg"]);
</script>
vue
<script setup lang="ts">
defineProps<{ msg?: string }>();
</script>
vue
<script>
export default {
  props: { msg: String },
};
</script>
<script setup>
defineProps();
</script>

如何使用

要通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "plugins": ["vue"],
  "rules": {
    "vue/valid-define-props": "error"
  }
}
bash
oxlint --deny vue/valid-define-props --vue-plugin

参考资料