Composable là function dùng Composition API để đóng gói và tái sử dụng stateful logic.
Ví dụ:
javascript
// useFetch.js
export function useFetch(url) {
const data = ref(null)
const loading = ref(true)
fetch(url).then(r => r.json()).then(d => { data.value = d; loading.value = false })
return { data, loading }
}So với Mixins:
- Không có naming collision — return value rõ ràng
- Source rõ ràng — biết data từ đâu
- Có thể nhận arguments (dynamic)
- Không có implicit state sharing
Mixins vẫn được hỗ trợ trong Vue 3 nhưng bị discouraged — Composition API là alternative được khuyến nghị.
A composable is a function using Composition API to encapsulate and reuse stateful logic.
Example:
javascript
// useFetch.js
export function useFetch(url) {
const data = ref(null)
const loading = ref(true)
fetch(url).then(r => r.json()).then(d => { data.value = d; loading.value = false })
return { data, loading }
}Vs Mixins:
- No naming collisions — explicit return values
- Clear source — know where data comes from
- Can accept arguments (dynamic)
- No implicit state sharing
Mixins are still supported in Vue 3 but discouraged — Composition API is the recommended alternative.