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
- Options API or Composition API: what is the difference, and which would you use?
- How do props work, and what is one-way data flow?
- How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
- computed, watch or watchEffect: when do you use each?
- ref or reactive: what is the difference, and when do you use each?
- How do you use Vue Router: dynamic routes, nested routes and navigation guards?
- Why does v-for need a key, and why should it not be the index?
- Pinia or Vuex: what is the difference, and why is Pinia now recommended?