Composition API
setup Syntax Sugar
Section titled “setup Syntax Sugar”Vue 3 introduces <script setup> syntax, providing a more concise way to write components.
<script setup>import { ref, computed } from 'vue'
const count = ref(0)const double = computed(() => count.value * 2)
const increment = () => { count.value++}</script>
<template> <div> <p>Count: {{ count }}</p> <p>Double: {{ double }}</p> <button @click="increment">Increment</button> </div></template>Lifecycle Hooks
Section titled “Lifecycle Hooks”<script setup>import { onMounted, onUpdated, onUnmounted} from 'vue'
// Component mountedonMounted(() => { console.log('Component mounted')})
// Component updatedonUpdated(() => { console.log('Component updated')})
// Component will unmountonUnmounted(() => { console.log('Component will unmount')})</script>Props and Emits
Section titled “Props and Emits”<script setup>// Define propsconst props = defineProps({ title: String, count: { type: Number, default: 0 }})
// Define emitsconst emit = defineEmits(['update', 'delete'])
const handleClick = () => { emit('update', props.count + 1)}</script>Custom Composables
Section titled “Custom Composables”Extract reusable logic.
import { ref, onMounted, onUnmounted } from 'vue'
export function useMouse() { const x = ref(0) const y = ref(0)
const update = (e) => { x.value = e.pageX y.value = e.pageY }
onMounted(() => window.addEventListener('mousemove', update)) onUnmounted(() => window.removeEventListener('mousemove', update))
return { x, y }}Usage:
<script setup>import { useMouse } from './composables/useMouse'
const { x, y } = useMouse()</script>
<template> <div>Mouse position: {{ x }}, {{ y }}</div></template>