What are Vue 3 composables and how do they improve on mixins?
// composables/usePagination.js
import { ref, computed } from 'vue'
export function usePagination(totalRef, perPage = 10) {
const currentPage = ref(1)
const totalPages = computed(() => Math.ceil(totalRef.value / perPage))
function nextPage() { if (currentPage.value < totalPages.value) currentPage.value++ }
function prevPage() { if (currentPage.value > 1) currentPage.value-- }
return { currentPage, totalPages, nextPage, prevPage }
}
// In any component — source is clear, no conflicts
const total = ref(100)
const { currentPage, totalPages, nextPage, prevPage } = usePagination(total, 20)
// Use multiple composables — no conflicts
const { query, results } = useSearch()
const { currentPage } = usePagination(results.total)
| Mixin | Composable | |
|---|---|---|
| Property source | Unclear | Explicit (destructured) |
| Name conflicts | Silent bug | Impossible |
| TypeScript | Poor | Excellent |
| Nesting composables | Messy | Clean |
All Comments