Vue3 Script Setup

Posted on  by admin

In this Vue tutorial we learn an easier way to use the Composition API in components with the script setup. We cover the lack of config object, how to use components, props and events and event data.

instructions

How to send events with the script setup. If you want to follow along with the examples, you will need to create an app generated by the Vue CLIas well as the following extra component.

The project should look similar to the following. TheGreetingMessagecomponent will have a paragraph with a simple greeting. The script setup is a different way for us to use the Composition API in components. Basically, we don’t need to use the config object and itssetupoption.

We can opt-in to the script setup by simply adding thesetupproperty to the script block’s tag.

We can also use it in combination with the regular script block.

Lesson Project

One of the great things about the script setup is that we need a lot less boilerplate. As an example, let’s consider the following. In the example above, we need the config object, thesetupoption and we need to return the “name” ref from it to be used in the template.

With the script setup block, we only need the ref and its import for it to work. A component only needs to be imported to be available, we don’t have to register it like we did before.

vscode supporting plug-ins

As an example, let’s import ourGreetingMessagecomponent into the root App component and invoke an instance of it in the template.

Consuming API

If we run the example in the browser,GreetingMessagerenders as expected. The file is a lot simpler, smaller and easier to read. In the Composition API, we access the props on a component instance by using thepropsobject from the setup option’s parameter list.

With the script setup, we define props withdefineProps, which takes a single argument.

Use props & emit & usecontext

Object with the prop and its type as key:value pair.

How to use props with the script setup

definePropsis actually a compiler macro that’s compiled away at build time and can only be used inside the script setup tag.

It doesn’t need to be imported, but theESLint pluginwill raise anundefwarning for it. In that case, we have two options to fix the warning. Explicitly import the macro from the core ‘vue’ package.

Define aglobal readonly variablefor it in your ESLint config file. The.eslintrc.jsconfig file can be found in your project’s root folder. To demonstrate, let’s change our example and let theGreetingMessagecomponent accept two props.

To keep the example simple, we’ll explicitly import thedefinePropsmacro. In the root App component, we can pass values to the two props on theGreetingMessagecomponent instance just like we normally would.

If we run the example in the browser, the greeting message will show the first and last names.

Migrate a component

In the Composition API, we send an event withcontext.emitfunction through a custom function. Then listen for the event in the parent component on the child component’s instance.

How to send events with the script setup

With the script setup, we define events withdefineEmits, which takes a single argument.

  • Array of events in string format.

  • The event is also sent through a custom function.

  • LikedefineProps, defineEmitsdefineEmitsis a macro.

It will also raise an ESLintundefwarning if we don’t import it explicitly or define a global variable.

How to use axios in Vue 3

To demonstrate, we’ll change our example to emit a “greet” event fromGreetingMessagewhen the user clicks a button.

  • To keep the example simple, we’ll import thedefineEmitsmacro explicitly. In the root App component, we’ll listen for the event and just invoke a function that displays an alert.

  • If we run the example in the browser and click the button, it will show the alert.

  • To send data with the event, we add the data as the second parameter when we emit the event.

Script setup and Computed

As an example, let’s add a name to the event inGreetingMessage. In the root App component, we’ll accept the data as a parameter to the custom function and use it in the alert.

What is the script setup?

When we run the example in the browser and click the button, it will show the greeting with the name.

For more information on the topics covered in this lesson, please see the relevant section below. 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:.

inheritAttrs

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.

This is the same for the components declaration!Importing the Image component is enough,and Vue understands that it is used in the template:we can remove the components declaration.

Closed by default and defineExpose

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:.

The last remaining syntax to migrate is the emits declaration. Vue offers a defineEmits helper, very similar to the defineProps helper.defineEmits returns the emit function:.

How to send data with events

script setup

Or even better, with TypeScript:. The full component declaration is 10 lines shorter.Not a bad reduction for a ~30 lines component!It’s easier to read, and plays better with TypeScript.It does feel a bit weird to have everything automatically exposed to the template,without writing return though, but you get used to it.

There is a more subtle difference between the two ways to declare components:a script setup component is “closed by default”.This means other components don’t see what’s defined inside the component.

For example, the Pony component can access the Image component(by using refs, as we’ll see in a following chapter).If Image is defined with defineComponent,then everything returned by the setup function is also visible for the parent component (Pony).If Image is defined with script setup,then nothing is visible for the parent component.Image can pick what is exposed by adding a defineExpose({ key: value }) helper.Then the exposed value will be accessible as key.

This syntax is now the recommended way to declare your components,and it’s awesome to use! Our ebook, online training and training are up-to-date with these changes if you want to learn more!

Please enable JavaScript to view the comments powered by Disqus.blog comments powered by Disqus.

< script setup > is a new syntax sugar from Vue3.