🎓 A1Learner
🔍
0 of 50 lessons completed

script setup in Depth

script setup is the short way to write a component script. Top-level bindings in script setup reach the template with no extra step.

Import at the top

The import brings ref in from vue.

import { ref } from 'vue'

A top-level binding

greeting is a ref declared at the top level.

const greeting = ref('Hello from script setup!')

The template sees it

The paragraph reads greeting with no return line.

<p>{{ greeting }}</p>

Example

<script setup>
import { ref } from 'vue'
const greeting = ref('Hello from script setup!')
const name = 'Vue'
function shout() {
  greeting.value = 'Hello, ' + name + '!'
}
</script>
<template>
  <div>
    <p>{{ greeting }}</p>
    <button @click="shout">Shout</button>
  </div>
</template>

Key points

  • Imports at the top of script setup bring in Vue functions like ref.
  • A const declared at the top level is visible in the template at once.
  • A function declared at the top level is callable from the template at once.
  • There is no return line, because the template already sees every top-level binding.
  • script setup has no export default line, because the block itself is the component script.

In this example, the script imports ref from vue. greeting is a top-level ref, and name is a top-level const. shout is a top-level function that sets greeting to Hello, Vue. The template reads greeting and calls shout from the button, with no return line anywhere. The first render shows Hello from script setup. A verified variant with greeting set to Hello, Vue shows the result of a shout.

Note

Imports must sit at the top, before the code that uses them.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does the template reach a top-level const in script setup?