• 本章主要涉及api内容:defineProps、withDefaults;
  • defineProps  只能是要么使用`运行时声明`,要么使用`typescript类型声明`。同时使用两种声明方式会导致编译报错。;
  • defineProps、withDefaults 是只在 <script setup> 语法糖中才能使用的编译器宏。他不需要导入且会随着 <script setup> 处理过程一同被编译掉。

  • withDefaults 只能与基于类型的defineProps声明一起使用;


例子1 > 运行时声明 的方式只能设置参数类型、默认值、是否必传、自定义验证。报错为控制台warn警告。

若想设置[ 编辑器报错、编辑器语法提示 ]则需要使用类型声明的方式。

<script lang='ts' setup>
const props = defineProps({
  child: {
    type:String, // 参数类型
    default: 1, //默认值
    required: true, //是否必传
    validator: value => {
      return value >= 0 // 除了验证是否符合type的类型,此处再判断该值结果是否符合验证
    }
  },
  sda: String, //undefined
  strData: String,
  arrFor: Array
})
</script>

子组件声明了的 props ,若父组件未传,则该值为 undefined 


例子2 > 类型声明的方式1:defineProps 单独使用该api,只能设置是否必传和参数类型。(利用TS特性)

<script lang='ts' setup>
const props = defineProps<{
  either: '必传且限定'|'其中一个'|'值', // 利用TS:限定父组件传 either 的值
  child?: string|number,
  strData?: string,
  arrFor: any[]
}>();
console.log(props);
</script>

相较于例子1,该写法只能设置参数类型、父组件对应 prop 是否该必传的功能。 

传值有误时,控制台报warn警告,还提供编辑器报错功能。

提供编辑器代码提示的功能。


 例子3 > 类型声明的方式2:在类型方式1的基础上,增加了设置 prop 默认值

<script lang='ts' setup>
interface Props {
  either: '必传且限定'|'其中一个'|'值', // 利用TS:限定父组件传 either 的值
  child: string|number,
  sda?: string, // 未设置默认值,为 undefined
  strData: string,
  msg?: string
  labels?: string[],
  obj?:{a:number}
}
const props = withDefaults(defineProps<Props>(), {
  msg: 'hello',
  labels: () => ['one', 'two'],
  obj: () => { return {a:2} }
})
</script>

注意:默认值为引用类型的,需要包装一个函数 return 出去。


QQ交流群:522976012  ,欢迎来玩

聚焦vue3,但不限于vue,任何前端问题,究其本质,值得讨论,研究与学习。
 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐