What are Vue 3 composables and how do they replace mixins?

What are Vue 3 composables and how do they replace mixins?

What are Vue 3 composables and how do they replace mixins?

Question

What are Vue 3 composables and how do they improve on mixins?

Answer

Problems with Mixins

  • Unclear source — hard to tell where a property comes from when multiple mixins are used
  • Naming conflicts — two mixins defining the same property causes silent bugs
  • Implicit dependencies — mixins can depend on each other in non-obvious ways
  • Poor TypeScript — types don't carry over properly

Composables — The Solution

// 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)

Key Advantages over Mixins

MixinComposable
Property sourceUnclearExplicit (destructured)
Name conflictsSilent bugImpossible
TypeScriptPoorExcellent
Nesting composablesMessyClean
All Comments