defineProps、withDefaults
1. defineProps
Vue 3 提供的宏,用于在
<script setup>中定义组件接收的 props
- 括号内的泛型
<{}>指定了 props 的类型结构
例子:
const props = withDefaults(defineProps<{ active?: boolean }>(), { active: false });
意思说明:
这行代码创建了一个 props 对象,其中:
- 如果父组件传递了 active 属性,则使用传递的值
- 如果父组件未传递 active 属性,则默认值为
false- 在组件内部通过 props.active 访问该属性值
2. 类型定义
{ active?: boolean }
active - 属性名称
?- 表示可选属性(可以不传递)boolean- 属性的数据类型为布尔值3.withDefaults
- 为 props 设置默认值
- 第二个参数
{ active: false }指定 active 属性的默认值为false
4.Vue2.0中的prop语法
export default {
props: {
active: {
type: Boolean,
default: false
}
}
}
Record 类型 -TypeScript内置的工具类型
const PAYMENT_COLORS: Record<string, string> = {
a: "#faad14",
b: "#000000",
c: "#1890FF",
d: "#07c160",
all: "#F56C6C"
};
语法结构
Record<K, T>
K- 键(key)的类型T- 值(value)的类型
作用:
- 定义一个对象,键为字符串类型,值也为字符串类型
- 提供类型安全,确保对象结构符合预期
- 在访问对象属性时提供类型检查
as const - TypeScript 的常量断言
代码
没使用as const
const SERIES_KEYS = ["type1", "type2", "type2", "type3", "type4"];
// 类型推断为: string[]
// 可以修改数组、添加元素等
使用as const
const SERIES_KEYS = ["type1", "type2", "type3", "type4", "type5"] as const;
//类型推断为: readonly
作用:
1. 类型更精确
- 每个元素都被视为字面量类型(literal type)
- 不是宽化的 string 类型,而是具体的值类型
2. 数组变为只读
- 数组不可修改(不能 push、pop、splice 等)
- 提供运行时保护