vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

323 - Prop Validation

Open Hacker-C opened this issue 2 years ago • 0 comments

  • Prop Validation(Props 类型校验)
  • Vue3 docs: https://vuejs.org/guide/components/props.html#prop-validation
  • More: https://github.com/Hacker-C/solutions-for-vuejs-challenges

Button.vue:

<script setup lang="ts">
// - Prop Validation(Props 类型校验)
// - Vue3 docs: https://vuejs.org/guide/components/props.html#prop-validation
defineProps({
  type: {
    default: 'default',
    required: false,
    validator(value: string) {
      return ['primary', 'ghost', 'dashed', 'link', 'text', 'default'].includes(value)
    }
  }
})

// You can also use ts interface:
// interface Props {
//   type?: 'primary' | 'ghost' | 'dashed' | 'link' | 'text' | 'default'
// }

// const { type = 'default' } = defineProps<Props>()
</script>

<template>
  <button>{{ type }}</button>
</template>

App.vue:

<script setup>
import Button from './Button.vue'
</script>

<template>
  <!-- link  -->
  <Button type="link" />
  <!-- defualt  -->
  <Button />
  <!-- invalid  -->
  <Button type="invalid" />
</template>

Hacker-C avatar Jul 30 '22 01:07 Hacker-C