webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.69k stars 188 forks source link

323 - Prop验证 #2721

Open Ly-TiR opened 2 months ago

Ly-TiR commented 2 months ago
//App.vue
<script setup>
import Button from "./Button.vue"
import {ref} from 'vue'

const type = ref()
</script>

<template>
  <Button :type="type" />
</template>

使用withDefaults进行校验

//Button.vue
<script setup lang="ts">
import {withDefaults} from 'vue';

interface Props{
  type?:("primary"| "ghost" | "dashed" | "link" | "text" | "default")
}

const props = withDefaults(defineProps<Props>(),{
    type:"default",
  })
</script>

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

使用自定义验证规则进行校验

//Button.vue
<script setup lang="ts">
const props = defineProps({
  type: {
    type: String,
    required: true,
    default: 'default',
    validator: (value:string) => {
      return ['primary', 'ghost', 'dashed', 'link', 'text', 'default'].includes(
        value,
      )
    },
  },
})
</script>

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