Skip to content
← Back to rules

vue/valid-define-props 正确性

An auto-fix is available for this rule.

它的作用

在 Vue 中强制正确使用 defineProps 编译器宏。

此规则在以下情况下会报告 defineProps 编译器宏:

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

为什么这不好?

错误使用 defineProps 可能会导致运行时错误和类型安全性丧失。 Vue 仍然可能编译通过,但 props 可能会静默失败,或者类型注解可能不正确。

示例

以下代码示例对这个规则来说是错误的:

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>

How to Use

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

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

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

版本

此规则在 v1.15.0 中加入。

参考资料