Search code examples
typescriptvuejs3vue-composition-apivue-validator

Vue 3 script setup prop validation typescript


I'm trying to replace my Vue 2 options API props object code with Vue 3 script setup syntax in TypeScript.

Existing:

type: {
  type: String,
  default: 'button',
  validator: (prop) => ['button', 'submit', 'reset'].includes(prop)
}

I have this so far:

<script lang="ts" setup>
interface Props {
  type?: string;
}

const props = withDefaults(defineProps<Props>(), { type: 'button' });
</script>

But I can't find any info on how to handle prop validators in the script setup syntax.


Solution

  • For those also arriving from Google, and since the Vue docs aren't very clear on this, you can do a straight conversion using the Vue 2 style options format as well:

    const props = defineProps({
      type: {
        type: String,
        default: 'button',
        validator: (prop) => ['button', 'submit', 'reset'].includes(prop)
      }
    })