Vue3 Script Setup Props

Posted on  by admin
Vue 3.2 introduced the script setup syntax,a slightly less verbose way to declare a component.You enable it by adding a setup attribute to the script element of your SFC,and you can then remove a bit of boilerplate in your component.

Let’s take a practical example, and migrate it to this syntax! The following Pony component has two props (the ponyModel to display, and a isRunning flag).Based on these two props, a URL is computed for the image of the pony displayed in the template(via another Image component).The component also emits a selected event when the user clicks on it.

As a first step, add the setup attribute to the script element.Then, we just need to keep the content of the setup function:all the boilerplate can go away.You can remove the defineComponent and setup functions inside script:.

We can also remove the return at the end:all the top-level bindings declared inside a script setup (and all imports)are automatically available in the template.So here ponyImageUrl and clicked are available without needing to return them.

tony19
95.4k

We’re nearly there: we now need to migrate the props and emits declarations. Vue offers a defineProps helper that you can use to define your props.It’s a compile-time helper (a macro), so you don’t need to import it in your code:Vue automatically understands it when it compiles the component.

defineProps returns the props:. defineProps receives the former props declaration as a parameter.But we can do even better for TypeScript users!

defineProps is generically typed:you can call it without a parameter,but specify an interface as the “shape” of the props.No more horrible Object as PropType to write!We can use proper TypeScript types,and add ? to mark a prop as not required 😍. We lost a bit of information though.In the previous version, we could specify that isRunning had a default value of false.To have the same behavior, we can use the withDefaults helper:.

tony19tony19
95.4k

# 结语