Skip to content

props 和 emit 推荐定义方式

使用 defineProps | defineEmitsts 类型方式定义更加灵活,类型提示更加丰富

vue
<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    value: string; // 必传字符串参数
    title?: string; // 可选字符串参数
    array?: string[]; // 可选数组参数
    showClose?: boolean; // 可选布尔参数
  }>(),
  {
    title: '', // 配置默认值
    array: () => []
  }
);

const emit = defineEmits<{
  (e: 'update:value', v: string): void;
  (e: 'update:array', v: string[]): void;
  (e: 'submit', v: string): void;
}>();
</script>
vue
<script setup lang="ts">
// 不建议使用此方式,书写麻烦,类型提示不友好
import { PropType } from 'vue';
const props = defineProps({
  value: { type: String, required: true },
  title: { type: String, default: '' },
  array: { type: Array as PropType<string[]>, default: () => [] },
  showClose: { type: Boolean }
});

const emit = defineEmits(['update:value', 'update:array', 'submit']);
</script>

TIP

withDefaults 设置 props 默认值

TIP

父级在使用此组件传 props 时会有类型提示和限制,此组件 emit 事件时也会有类型提示和限制