snippetjavascriptvueModeratepending
Vue 3 Composition API - ref, reactive, and composables
Viewed 0 times
vue 3composition APIrefreactivecomposablessetup
Problem
Vue 3's Composition API is powerful but the difference between ref and reactive, plus when to extract composables, isn't immediately clear.
Solution
Vue 3 Composition API patterns:
<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
// ref: for primitives and objects you may reassign
const count = ref(0)
const user = ref(null) // Will be reassigned to object
// reactive: for objects you'll mutate
const form = reactive({
name: '',
email: '',
errors: {}
})
// Computed
const isValid = computed(() => form.name && form.email)
// Watch
watch(() => form.email, (newVal) => {
form.errors.email = !newVal.includes('@') ? 'Invalid' : ''
})
// Lifecycle
onMounted(async () => {
user.value = await fetchUser()
})
</script>// Composable (reusable logic, like React hooks)
// composables/useFetch.js
import { ref, watchEffect } from 'vue'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(true)
watchEffect(async () => {
loading.value = true
try {
const res = await fetch(url.value || url)
data.value = await res.json()
} catch (e) {
error.value = e
} finally {
loading.value = false
}
})
return { data, error, loading }
}
// Usage in component
const { data: users, loading } = useFetch('/api/users')Why
The Composition API solves the 'feature spread' problem of Options API where related code is scattered across data, methods, computed, and watch. With composition, all code for one feature stays together.
Gotchas
- ref.value is needed in JS but NOT in templates - Vue auto-unwraps refs in templates
- reactive() loses reactivity if destructured - use toRefs() to preserve it
Context
Building Vue 3 applications with Composition API
Revisions (0)
No revisions yet.