您的位置:首页 > 技术中心 > 前端框架 >

vue3中怎么使用props和emits并指定其类型与默认值

时间:2023-05-19 19:28

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 定义接收的类型。

当然,你可以使用与 JavaScript 环境相同的方式来定义 props,但这种做法会削弱使用 TypeScript 的意义。

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 的方式使用,那么就没有发挥出的作用。

特别是在大规模项目中触发数据类型可能会出现意料之外的错误,因此需要定位错误可能需要花费数小时的时间。可能出现魔法字符串的错误写法,导致无法达到预期的事件触发效果。

以上就是vue3中怎么使用props和emits并指定其类型与默认值的详细内容,更多请关注Gxl网其它相关文章!

本类排行

今日推荐

热门手游