Composables and mixins help you reuse code in Vue components. They make your code cleaner and easier to manage.
0
0
Composable vs mixin comparison in Vue
Introduction
You want to share logic between multiple components.
You need to organize code by feature instead of by component.
You want to avoid repeating the same code in many places.
You want better control over code reuse and avoid conflicts.
You want to write easier-to-understand and maintainable Vue apps.
Syntax
Vue
/* Mixin example */ export const myMixin = { data() { return { count: 0 }; }, methods: { increment() { this.count++; } } }; /* Composable example */ import { ref } from 'vue'; export function useCounter() { const count = ref(0); function increment() { count.value++; } return { count, increment }; }
Mixins are objects with options like data and methods.
Composables are functions that use Vue's reactive features and return state and functions.
Examples
This component uses the mixin to get count and increment method.
Vue
/* Using a mixin in a component */ import { myMixin } from './mixins'; export default { mixins: [myMixin], mounted() { this.increment(); console.log(this.count); } };
This component calls the composable function inside setup and uses its state and methods.
Vue
/* Using a composable in a component */ import { useCounter } from './composables'; import { defineComponent } from 'vue'; export default defineComponent({ setup() { const { count, increment } = useCounter(); increment(); console.log(count.value); return { count, increment }; } });
Sample Program
This Vue component uses a composable to manage a toggle state. It toggles the state twice and logs the final value.
Vue
<script setup> import { ref } from 'vue'; // Composable function function useToggle() { const isOn = ref(false); function toggle() { isOn.value = !isOn.value; } return { isOn, toggle }; } // Using composable const { isOn, toggle } = useToggle(); // Toggle twice toggle(); toggle(); console.log(isOn.value); </script>
OutputSuccess
Important Notes
Mixins can cause name conflicts if multiple mixins have the same property names.
Composables avoid conflicts by using local variables and returning only what you want.
Composables work better with TypeScript and modern Vue features.
Summary
Mixins are older and use Vue options like data and methods.
Composables are functions that use Vue's Composition API for better code reuse.
Prefer composables for clearer, safer, and more flexible code sharing.