setup()
setup is the entry point of the Composition API: it runs before the component is created and returns what the template can use.
In this page:
Syntax
export default {
setup() {
const name = ref(initial_value);
const doubled = computed(() => name.value * 2);
function method() { name.value++; }
return { name, doubled, method };
}
}
setup()
Inside setup you declare reactive state with ref and reactive, computed values, functions and lifecycle hooks, then return an object of things to expose to the template.
It receives props and a context with emit, slots and attrs. There is no this inside setup.
Note:
The script setup syntax in single-file components removes the need to return values manually.
Example: setup()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<p>{{ greeting }} ({{ shout }})</p>
<button @click="setName('Grace')">Rename</button>
</div>
<script>
Vue.createApp({
setup() {
const name = Vue.ref("Ada");
const greeting = Vue.computed(() => "Hello, " + name.value);
const shout = Vue.computed(() => greeting.value.toUpperCase());
const setName = (n) => { name.value = n; };
return { greeting, shout, setName };
},
}).mount("#app");
document.querySelector("button").click();
Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>
<!-- Output:
Rendered: Hello, Grace (HELLO, GRACE)Rename
console: Hello, Grace (HELLO, GRACE)
-->
Live Example
Related Topics
Common Mistakes
- Using this inside setup
- Forgetting to return values
- Destructuring props and losing reactivity
Chapter Summary
- setup runs before the component is created
- Return what the template needs
- It receives props and context
- No this inside setup
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: