Home  >  Article  >  Web Front-end  >  How to use props and emits in vue3 and specify their type and default value

How to use props and emits in vue3 and specify their type and default value

王林
王林forward
2023-05-19 17:21:192533browse

Usage of defineProps

definePropsThere is no need to introduce it when using it. The default is the global method.

  • Used in vue3 projects developed by js

const props = defineProps({
  attr1: {
    type: String, // S 必须大写
    default: "",
  },
  attr2: Boolean,
  attr3: {
    type: Number,
    required: true,
  },
});

The usage in js environment is similar to that of vue2, except that the optional API is replaced by Composable API. The defined props type and default value are the same as the vue2 type. The definePropsAPI is used in vue3, which will not be introduced here.

  • Used in the vue3 project developed by ts

interface DeatilInf {
  aaa: string;
  bbb: number;
}

const props = withDefaults(
  // 参数一:定义props类型:? 代表非必传字段, :号后面紧跟的是数据类型或自定义接口, | 或多种类型
  defineProps<{
    name: string;
    age?: number;
    detail?: DeatilInf | any;
  }>(),
  // 参数二:指定非必传字段的默认值
  {
    age: 18,
    detail: {},
  }
);

Use typeScript to develop the vue3 project to define props. There are two main APIs used: defineProps Define the received props, withDefaults Define the received type.

Of course, you can define props in the same way as a JavaScript environment, but this defeats the point of using TypeScript.

The use of defineEmits

is different from vue2: vue3 needs to define the event before triggering the event. In Vue3, `defineEmits` is also a global API

  • Used in js

const emits = defineEmits(["change", "input"]);
emits("chage", "data");
emits("input", { data: 123 });
  • Used in 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");

The above code uses enumerationenum to avoid the appearance of "magic strings". It is worth mentioning that js can also be used in ts, so it will not play its role.

Especially in large-scale projects, unexpected errors may occur when triggering data types, so it may take hours to locate the error. The magic string may be written incorrectly, resulting in the failure to achieve the expected event triggering effect.

The above is the detailed content of How to use props and emits in vue3 and specify their type and default value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete