Mixin Fundamentals
Mixins provide a flexible mechanism for distributing reusable functionalities in Vue components. A mixin object can contain any component option. When a component incorporates a mixin, all options from the mixin object are merged into the component's own options.
Component-Level Mixins
Component-level mixins affect only the specific component where they are defined.
<template>
<div>
<p>{{ textContent }}</p>
</div>
</template>
<script>
const customMixin = {
data() {
return {
textContent: 'Initial text',
};
},
mounted() {
console.log('Mixin lifecycle hook executed');
}
};
export default {
name: 'SampleComponent',
mixins: [customMixin],
mounted() {
console.log('Component lifecycle hook executed');
}
};
</script>
Merge Behavior:
- Conflicting data properties are resolved in favor of the component's data.
- Lifecycle hooks with identical names are merged into an array and invoked sequentially, with mixin hooks called before the component's own hooks.
- Options expecting objects, such as
methods,components, anddirectives, are merged into a single object. Conflicting keys are resolved by prioritizing the component's options.
The expected console output is:
- 'Mixin lifecycle hook executed'
- 'Component lifecycle hook executed'
Global-Level Mixins
Global mixins affect every Vue instance created after their registration and should be used judiciously.
// main.js or entry file
import Vue from 'vue';
Vue.mixin({
created() {
console.log('Global mixin hook triggered');
}
});
With this global mixin, the created hook will execute for every component instance.