Script Setup — Transcript

Transcript of the free Vue.js lesson Script Setupwatch the video lesson.

In a previous video, when we were setting up Vite, you might remember Vite scaffolding a script section for us with a setup attribute on it. It looked something like this. The purpose of the script setup attribute is to automatically expose all the top level bindings in a single fall component to the template. In other words, it makes it so that we don't have to return the variables we want available in the template from the setup function.

2. Let's see it in action. vue, we can add the setup attribute to the script tag, and then move everything except for the return statement out of the setup function to just inside the script tag. And with that, we no longer need to export anything.

Even the registration of the yummy meal component is no longer necessary. the simple fact of importing it is good enough for view with the setup attribute. In the browser, nothing's changed. Perfect.

Let's do the same thing for the yummy meal component. I'll add the setup attribute and move the code from inside setup to the root of the script tag. I'll also remove the return as it's no longer needed. We also no longer need to register the yummy meal price component.

but rather just importing it above is enough. Here we have an issue. What do we do with the prompts? Well, we've got two options.

We could create another script tag and register the prompts just as we normally would. Yeah, that works just as before. You can actually apply this approach of adding a second script tag for any of the options API stuff that you'd still like to use. However, For the props, we also have another option that doesn't require that we create a separate script tag.

We can call a special defineProps function. defineProps doesn't need to be imported, as it's a compiler micro, only usable inside of the script setup, and is compiled away at compile time. This brings up an important caveat to mention about the setup attribute. It is only available in single file components, where a build tool like Vite or Webpack is used to compile the single file component to the browser executable code.

While everything still looks good, clicking on the add to cart buttons doesn't work. And in the console, we have an error. Amit is not defined. We have to define Amit, much like we did with defined prompts.

Now everything is working again. Well, that's the gist of the setup attribute. Using it prevents us from having to provide much of the boilerplate code typical to the setup method. And who doesn't like to save some keystrokes?