这篇文章主要介绍了vue3中怎么使用props和emits并指定其类型与默认值的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇vue3中怎么使用props和emits并指定其类型与默认值文章都会有所收获,下面我们一起来看看吧。
defineProps 的使用
defineProps在使用的时候无需引入,默认是全局方法。
- 在 js 开发的 vue3 项目中使用 
const props = defineProps({
  attr1: {
    type: String, // S 必须大写
    default: "",
  },
  attr2: Boolean,
  attr3: {
    type: Number,
    required: true,
  },
});js 环境中使用与 vue2 的使用方法类似,只是选项式 API 换成了组合式 API。定义 props 类型与默认值都与 vue2 类型,vue3 中使用的是
definePropsAPI,在此不多介绍。
- 在 ts 开发的 vue3 项目中使用 
interface DeatilInf {
  aaa: string;
  bbb: number;
}
const props = withDefaults(
  // 参数一:定义props类型:? 代表非必传字段, :号后面紧跟的是数据类型或自定义接口, | 或多种类型
  defineProps<{
    name: string;
    age?: number;
    detail?: DeatilInf | any;
  }>(),
  // 参数二:指定非必传字段的默认值
  {
    age: 18,
    detail: {},
  }
);使用 typeScript 开发 vue3 项目定义 props 主要使用的 API 有两个:
defineProps定义接收的 props 、
withDefaults定义接收的类型。
当然,你也可以使用上述 js 环境使用的方法定义 props,但这样做就失去了使用 TS 的意义了。
defineEmits 的使用
与 vue2 不同:vue3 在触发事件之前需要定义事件。同样在 vue3 中 defineEmits 也是全局 API
- js 中使用 
const emits = defineEmits(["change", "input"]);
emits("chage", "data");
emits("input", { data: 123 });- TS 中使用 
enum EventName {
  CHANGE = "change",
  INPUT = "input",
}
const emits = defineEmits<{
  (event: EventName.CHANGE, data: string[]): void;
  (event: EventName.INPUT, data: string): void;
}>();
emits(EventName.CHANGE, ["data"]);
emits(EventName.INPUT, "123");上面的代码中使用了枚举
enum避免"魔法字符串"的出现。值得一提,ts 中也可以使用 js 的方式使用,那么就没有发挥出的作用。
尤其在大型项目里面触发数据的类型可能会出现意想不到的 bug,然后定位 bug 可能得花上好几个小时。也可能会出现触发事件的事件名字符串写错(俗称魔法字符串)导致达不到预期效果。