- \n
- {{ n }} \n
Vue 3
Composition API
Organize reactive state, computed, and lifecycle logic by feature.
By EZ4Code Team
composition-apiscript-setup
Code
<script setup>
import { ref, computed, onMounted } from "vue";
const items = ref([1, 2, 3]);
const doubled = computed(() => items.value.map(x => x * 2));
function add() {
items.value.push(items.value.length + 1);
}
onMounted(() => {
console.log("Component mounted");
});
</script>
<template>
<button @click="add">Add</button>
<ul>
<li v-for="n in doubled" :key="n">{{ n }}</li>
</ul>
</template>Explanation
The Composition API organizes component logic by feature rather than by option. Inside script setup, declared variables and functions are automatically available in the template. ref, computed, and lifecycle hooks replace the Options API's data, computed, and lifecycle methods.
More Vue 3 Snippets
Single-File Component
Define a Vue 3 component with script setup, template, and scoped styles.
Refs & Reactive
Choose between ref and reactive for reactive state.
Computed & Watch
Derive values with computed and react to changes with watch.
Props & Emits
Declare inputs and events, and implement v-model on a component.
Lifecycle Hooks
Register lifecycle callbacks as composable functions.
Slots & Scoped Slots
Distribute content with default, named, and scoped slots.