Vue Composition API State Definition

Organize component state with `ref` and `computed`, keeping logic separate from the view.

Vuejavascript
javascript
1import { ref, computed } from Vue;23export function useCart() {4  const items = ref([]);5  const total = computed(() =>6    items.value.reduce((sum, item) => sum + item.price * item.quantity, 0)7  );89  function add(item) {10    items.value.push(item);11  }1213  return { items, total, add };14}

Key Points

  • Encapsulate state and actions into functions for reuse across multiple components.
  • `computed` caches results and recalculates only when dependencies change.

Usage suggestions

Run the copied code in a local sample project first to verify expected behavior, then adapt the naming and structure to your business needs. Pasting directly into a large project can cause you to overlook contextual differences.