Vue.js Developer interview question · Most asked

What are composables, and why did they replace mixins?

Summary

Composables are functions that use the Composition API to encapsulate and reuse stateful logic, such as useFetch, useMouse or usePagination. They return refs and functions explicitly. Mixins merged options into components implicitly, which caused unclear property origins, name collisions and hidden coupling.

Longer Answer

With a composable you can see where every value comes from (const { data, error } = useFetch(url)), rename on destructuring, and pass arguments. Conventions: name them useX, accept refs or getters as inputs (toValue() normalises them), clean up side effects with onUnmounted or onScopeDispose, and return plain objects of refs. VueUse is a large collection of ready-made composables.

Code Example

import { ref, onMounted, onUnmounted } from "vue";

export function useWindowWidth() {
  const width = ref(window.innerWidth);
  const update = () => (width.value = window.innerWidth);
  onMounted(() => window.addEventListener("resize", update));
  onUnmounted(() => window.removeEventListener("resize", update));
  return { width };
}

Key Points

  • Functions encapsulating stateful logic.
  • Explicit inputs and outputs.
  • Mixins had collisions and hidden origins.
  • VueUse for common needs.

More most-asked Vue.js Developer questions

← All Vue.js Developer questions