Home / Blog / Vue.js Script Setup in Less than 5 Minutes
Vue.js Script Setup in Less than 5 Minutes

Vue.js Script Setup in Less than 5 Minutes

Daniel Kelly
Daniel Kelly
Updated: May 15th 2022

The Vue.js Composition API is a handy tool for creating reusable, stateful code across multiple components. However, it’s not just for creating reusable composables. The longer the API has been around, the more people are using it, even as their default style for all components.

Considering the workflow, it really makes a lot of sense. If many reusable pieces are now being made as composables, then writing your component specific logic in the Composition API, makes interacting with said composable a more seamless process.

The icing on the cake, that really makes this approach enjoyable, is the script setup syntax.

If you’ve used the Composition API and some of it has felt a little cumbersome then the script setup syntax is going to be a delight to use.

Let’s quickly take a look at how it works.

A Component WITHOUT Script Setup

Before script setup you might have had a component that looks like this:

<template>
    <MyComponent/>
    <button @click="greet">{{btnText}}</button>
</template>
<script>
import {ref} from "vue"
import MyComponent from "./MyComponent.vue"

export default{
  components:{ MyComponent },
    setup(){
    const btnText = ref("Greet Awesome Dev")
    const greet = ()=> alert("Hello!")
        return { btnText, greet }
  }
}
</script>

Notice a few things:

  1. We have to declare a setup method within the exported object

    export default {
      //...
      setup(){}
    }
  2. In order to register a component you have to import it and then register it with the components option

    
    import MyComponent from "./MyComponent.vue"
    //...
    components:{ MyComponent },
  3. Lastly, if we need access to anything within the setup method in the template it must be exported from setup

    return {btnText, greet}

None of these things are the end of the world but the experience could be better. Especially, #3. I can’t tell you how many times I’ve gotten my state and logic all setup, only to test things out and realize I forgot to add the return.

A Component WITH Script Setup

Now let’s take a look at the same component with script setup.

<template>
  <MyComponent/>
    <button @click="greet">{{btnText}}</button>
</template>
<script setup>
    import {ref} from "vue"
    import MyComponent from "./MyComponent.vue"
    const btnText = ref("Greet Awesome Dev")
    const greet = ()=> alert("Hello!")
</script>

Not only is this approach shorter but there is also less noise and less boilerplate. Let’s break it down:

  1. First, there’s no more setup method to declare and no more object to export. Instead we’ve simply added setup to the script tag.
  2. Component registration has been reduced to a single line (the import itself).
  3. Lastly, and probably most importantly, we never have to remember to return any data or functions to expose them to the template. It’s done automatically for us!

Isn’t that nice! It’s a fairly simple change but it really makes a world of difference when using the composition API on a regular basis.

Other Script Setup Tips

Finally, the simple steps provided above will get you by much of the time but there are a few other things worth mentioning.

Use it or Don’t

It’s not all or nothing. Script setup is totally opt-in and you can incrementally adopt it into your existing Vue 3 project. You can even use a traditional script tag in the same component alongside a script setup tag.


<script setup>
    //... logic and such
</script>
<script>
export default{
    name: "MyComponent",
    inheritAttrs: false,
  props:{
    msg: { type: String, default: "Hello!" }
  },
}
</script>

Defining props

To define props you could do it in a separate script tag as above but Vue also provides a compiler level micro called defineProps that allows you to do the same thing within script setup.

<script setup>
  const props = defineProps({
        msg: { type: String, default: "Hello!" }
    })
    //... logic and such
</script>

This is necessary if you need access to those props from within script setup.

Also, as a compiler micro, defineProps is only available inside of script setup and does not have to be imported.

Defining Emits

Like props a defineEmits micros is also provided to define what events your component can trigger, as well as provide you access to an emit function.

const emit = defineEmits(['updated', 'done'])
//...
emit("done")

A Feature for Built Projects

Lastly, script setup is a feature meant to be used in projects that include a build step. It relies on template compilation and typically you shouldn’t ship the template compiler to the browser.

However, if you want a quick start playground to mess around with script setup the official Vue SFC playground is a great option as well as https://vite.new/vue from Stackblitz.

Conclusion

The Composition API is a great addition to the Vue JavaScript framework and the script setup feature really makes it a feasible option for everyday, every-component use.

Related Courses

Start learning Vue.js for free

Daniel Kelly
Daniel Kelly
Daniel is the lead instructor at Vue School and enjoys helping other developers reach their full potential. He has 10+ years of developer experience using technologies including Vue.js, Nuxt.js, and Laravel.

Comments

Latest Vue School Articles

What Does the Vueniverse Look Like in 2025? Predictions for the Vue Ecosystem in the Year Ahead

What Does the Vueniverse Look Like in 2025? Predictions for the Vue Ecosystem in the Year Ahead

Vue.js enters 2025 from a position of strength, with a mature ecosystem and plenty of resources available to help it’s developers thrive. So what might 2025 look like for Vue developers?
Daniel Kelly
Daniel Kelly
Black Friday Deals: Build Better Vue.js Apps for Less

Black Friday Deals: Build Better Vue.js Apps for Less

Unlock the ultimate Black Friday deals at Vue School and take your skills to the next level. Learn from expert developers, build production-ready apps, and save up to 60% on comprehensive courses, certifications, and bundles tailored for modern developers
Maria Panagiotidou
Maria Panagiotidou

Our goal is to be the number one source of Vue.js knowledge for all skill levels. We offer the knowledge of our industry leaders through awesome video courses for a ridiculously low price.

More than 200.000 users have already joined us. You are welcome too!

Follow us on Social

© All rights reserved. Made with ❤️ by BitterBrains, Inc.