IT评测·应用市场-qidao123.com技术社区

标题: [Vue3]绑定props 默认值 [打印本页]

作者: 泉缘泉    时间: 昨天 05:25
标题: [Vue3]绑定props 默认值
前言

   使用TS、Vue3组织组件中传入props的通用方式
  步调

步调1:使用 defineProps 界说 Props

使用interface界说props中各项的类型:
  1. // 组件List.vue
  2. // 定义 Props 类型和接口
  3. interface ListItem {
  4.   name: string;
  5.   time: string;
  6.   content: {
  7.     status: number;
  8.     name: string;
  9.   }[];
  10. }
  11. // 使用 defineProps 定义 Props
  12. const props = defineProps<{
  13.   listData?: ListItem[]; // listData 属性为可选的 ListItem 数组类型
  14. }>();
复制代码
步调二:设置默认值

使用Vue3中的withDefaults界说props默认值
  1. // 组件List.vue
  2. // 定义 Props 类型和接口
  3. interface ListItem {
  4.   name: string;
  5.   time: string;
  6.   content: {
  7.     status: number;
  8.     name: string;
  9.   }[];
  10. }
  11. // 使用 withDefaults 设置默认值
  12. const props = withDefaults(
  13.   defineProps<{
  14.     listData?: ListItem[]; // listData 属性为可选的 ListItem 数组类型
  15.   }>(),
  16.   {
  17.     listData: () => [], // 设置 listData 的默认值为空数组
  18.   }
  19. );
复制代码
之后组件中即可使用props.listData来访问props中的值。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4