working and Using Vuejs mixins
Using Vuejs mixins is a way to re-use functionality across multiple components in your web application. This is a good idea if you have multiple components sharing the same functionalities. Vuejs Mixins can contain any component options and when used, they are combined with the component’s options.
How to use mixins in Vue
Firstly, you need to create an object where all the component options will be placed.
Create a file which the mixins will be created and exported for reuse:
// in src/mixins/createdHook.js
export defult {
created(){
console.log('created hook from mixin!')
}
}
And to register the mixin in a component, we use the mixins
option in the component after importing the file.
import Vue from 'vue';
import createdHook from '@/mixins/createdHook.js';
...
const vm = new Vue({
mixins: [createdHook]
});
// => 'created hook from mixin!'
Merging options in components
If a mixin has overlapping options with a component, the two will be merged with the component’s data
and methods
option having a higher priority. For lifecycle hooks, they will both be called with the mixin’s hooks called first. So if the two contain a lifecycle hook of mounted, both hook functions will be added to an array and the mixin’s hook function called first.
const mixin = {
data(){
return {
message: 'Hello world'
}
},
mounted(){
console.log('mounted hook in mixin was called');
}
}
const vm = new Vue ({
mixins: [ mixin ],
data(){
return { message: 'new message!'}
},
methods: {
logMessage(){
console.log(this.message)
}
},
mounted(){
console.log('mounted hook in the component was called');
}
})
// => 'mounted hook in mixin was called'
// => 'mounted hook in the component was called'
vm.logMessage(); // => 'new message!'
check out this part of the docs to know more.
Registering global mixins
You can register mixins for use globally using Vue.mixin()
, you have to be careful when using because this will affect every component instance created in the application.
Vue.mixin({
data(){
return {
greeting: 'Good morning!'
}
}
});
const vm = new Vue ({
data(){
return{
greeting: 'Good evening!'
}
},
created(){ console.log(this.greeting)}
});
// ==> 'Good evening!'
Notice how there was no need to include the mixins
option in the component.
Conclusion
Earlier in this article, I stated how mixins are a good idea of you need to share functionalities across components. That is what mixins should only be used for. Do not use mixins to share state globally in your applications, make use of the official state manage library Vuex instead.