<script setup> syntax in Vue 3

Reduce code and improve performance

November 2021

Vue 3 provides an optional <script setup> syntax, described as 'syntactic sugar' when using the Composition API. From the docs:

It is the recommended syntax if you are using both SFCs and Composition API. It provides a number of advantages over the normal <script> syntax:

  • More succinct code with less boilerplate
  • Ability to declare props and emitted events using pure TypeScript
  • Better runtime performance (the template is compiled into a render function in the same scope, without an intermediate proxy)
  • Better IDE type-inference performance (less work for the language server to extract types from code)

Using my recent Vue 3 Autocomplete as an example:

<script>

// Changes to:
  
<script setup>

The export and setup blocks can now be removed:

export default {
  setup() {
    let searchTerm = ref('')
    ...

// Changes to:

let searchTerm = ref('')

And the block where variables, components etc. are returned for use in the template can be removed entirely:

return {
  countries,
  searchTerm,
  searchCountries,
  selectCountry,
  selectedCountry
}

/* The above is no longer needed as any variables, components etc. are 
automatically available in the template */

This is a small update to make to a component, reducing lines of code and providing a number of other benefits. For more information on how to use props, events and more with this syntax check the docs.


Sign up for my newsletter

Get notified when I post a new article. Unsubscribe at any time, and I promise not to send any spam :)

© Steven Cotterill 2021