...

/

Script Setup and Reactivity

Script Setup and Reactivity

Understand the benefits of the script setup syntax and how to add reactivity.

Script setup

This example shows the Composition API, which includes a setup section:

Press + to interact
<script>
export default {
setup() {
const user = {}
function getUser() {}
onMounted(getUser) // get user when component mounts to the DOM
const products = []
function getProducts() {}
onMounted(getProducts) // get products when component mounts to the DOM
const basket = []
// computed value updates when a value inside changes:
const showBasket = computed(() => basket.length > 0 ? true : false)
function updateBasket(item) {}
return { user, getUser, products, getProducts, ...}
}
}
</script>
  • Lines 4–20: This is the setup() wrapper containing all of the composition code.

While still valid to use, we also have a way to make this shorter and cleaner, using <script setup> inside single file components. We briefly looked at this in earlier examples, and it is now the recommended syntax. It involves removing the setup() wrapper, export default, and the return section. Our above ...