Vue.js Script Setup in Less than 5 Minutes

Written by Daniel Kelly

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

Learn Vue.js 3 With Vue School

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.

Learn Vue.js 3 With Vue School

Leave a Reply

Your email address will not be published. Required fields are marked *

Up Next:

Tooling Saves Your Bacon

Tooling Saves Your Bacon