Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 794
Titan Avatar asked Jul 14 '26 23:07

Titan


2 Answers

You can use in defineProps the same structure as in Options API. (DOCS)

<script lang="ts" setup> 
  const props = defineProps({ 
    type: {
      type: String as PropType<'button' | 'submit' | 'reset'>,
      default: 'button',
      validator: (prop: Type) => ['button', 'submit', 'reset'].includes(prop)
    }
  });
</script>
like image 187
Orbis Avatar answered Jul 17 '26 20:07

Orbis


I believe I've worked it out, still new to typescript but this should be the equivalent (will be validated in typescript rather than vue runtime)

interface Props {
  type?: 'button' | 'submit' | 'reset';
}
like image 44
Titan Avatar answered Jul 17 '26 20:07

Titan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!