Up until Vue 3, developers organized code using the "Options API" (data, methods, computed).
As components grew extremely large, logically related code became fragmented across those different option blocks.
To solve this, Vue 3 introduced the Composition API, allowing developers to group logic together cleanly.
<script setup> SyntaxThe easiest way to use the Composition API is inside Single File Components using <script setup>.
This special tag tells Vue to automatically execute everything inside it during component setup.
Any variable or function declared inside <script setup> is instantly available to the HTML template!
In the Options API, variables inside data() were automatically reactive.
In the Composition API, standard variables are completely static and will not update the DOM.
To make a primitive value (string, number, boolean) reactive, you must wrap it in the ref() function.
<script setup>
import { ref } from 'vue'
// 'count' is now a reactive object
const count = ref(0)
function increment() {
// You must append .value in JavaScript to change it!
count.value++
}
</script>
Notice that when modifying the value inside JavaScript, you must type .value.
However, when using it in the HTML template (like {{ count }}), Vue automatically unwraps it for you!
If you need to declare an entire object or array with many properties, use reactive() instead of ref().
reactive() does not require you to append .value when accessing its properties.
<script setup>
import { reactive } from 'vue'
const state = reactive({ count: 0, user: 'John' })
// No .value needed for reactive objects!
state.count++
</script>
When modifying a variable created with ref() inside your JavaScript code, what property must you access?
What is a primary benefit of using the Composition API over the classic Options API?