我刚刚发现,不要像这样定义组件的属性:
const props = defineProps({
id: Number,
title: String,
name: String,
})
我可以这样做:
defineProps([
'id',
'title',
'name',
])
这似乎不需要 type 声明,但是这样做有什么缺点吗? vue是否自己确定每个属性的type?
我正在使用 script setup。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这不仅仅是
type声明。这是一个道具验证功能。 完整的语法是
const props = defineProps({ name: String, id: [ Number, String ], style: { type: Object, default: ()=>{ color: "red", bg-color: "white" }, validator: function (value) { return ['red', 'blue', 'green'].includes(value.color) } }, })因此,仅使用命名道具的缺点是:
类型安全。但即使在typed props的情况下,它也只会在开发构建中显示控制台警告。而使用 prop 定义的优点是
types缺点当然是安全性较差。
vue 会自行确定每个属性的类型吗? 不会
当提供字符串数组时,Vue 根本不会验证传递的 props 的类型,因此如果使用不正确(这种情况更有可能发生,因为其他开发者/未来你无法知道应该传递什么不阅读组件的其余代码)您最终会在组件中的某个位置出现一些运行时错误,而不是关于作为 prop 传递的错误值的干净错误/警告(或来自 IDE 的合理错误)
大多数时候,您应该使用尽可能多的具体道具定义。