Intermediate LevelVue JS
What are Vue Composables and why did they replace legacy Mixins?
❓ Interview Prompt: Explain Vue Composables, how they solve Mixin namespace collisions and implicit dependencies, and writing reusable composables.
A Composable is a function that leverages Vue Composition API ('ref', 'computed', 'onMounted') to encapsulate and reuse stateful logic across components.
Why Composables Replaced Mixins:
In Vue 2, Mixins were used for code reuse, but suffered from three fatal flaws:
1
Namespace Collisions: If two mixins declared a property named 'isLoading', they silently overwrote each other.
2
Implicit Dependencies: Impossible to tell where a property in a component came from when multiple mixins were included.
3
No Parameter Passing: Mixins could not easily accept configuration parameters.
How Composables Solve This:
Composables are standard JavaScript functions. When calling 'const { data: userData, isLoading: userLoading } = useFetch("/api/user")', you explicitly destructure and rename properties, eliminating collisions!
Code Implementation Example
javascript
// composables/useMousePosition.js
import { ref, onMounted, onUnmounted } from 'vue';
export function useMousePosition() {
const x = ref(0);
const y = ref(0);
function updatePosition(event) {
x.value = event.pageX;
y.value = event.pageY;
}
onMounted(() => window.addEventListener('mousemove', updatePosition));
onUnmounted(() => window.removeEventListener('mousemove', updatePosition));
return { x, y };
}💡Reusable Vue Composable encapsulating mouse tracking lifecycle and state.
🎯 Interview Key Takeaway
Composables use Composition API to share stateful logic without Mixin namespace collisions or implicit dependency confusion.
#Composables#Mixins#Reusability#Intermediate
Back to all Vue JS Questions→