Vue Js Use Mixins

Mixins are Help to adding more functionality for vue instance and vue components. So we Can share mixins between multiple components and multiple places in vue project

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

What Is Mixins

As the name goes – “Mix – In”, Mixin gives us a way to distribute reusable functionality in Vue components. These reusable functions are merged with existing functions.

Basic example

const myMixin = {
created(){
  console.log("It works!")
 }
}
var app = new Vue({
  el: '#root',
  mixins: [myMixin]
})// It works!

if you are using mixins you can add and merge more data to the component as your desire. following example using vue2.

<div>
 <h2>{{devname}}</h2>
 <h2>{{mixinname}}</h2&amp;>
</div>

const mymixins = {
 data() {
 return {
 mixinname:"Try n Dev In mixins"
 }
}
}
  export default {
  mixins:[mymixins],
  data() {
  return {
    devname:"Try n Dev"
  }
 }
}

Merging

By default, mixins will be applied first, and the component will be applied second so that we can override it as necessary. The component has the last say. This only really becomes important when there is a conflict and the component has to “decide” which one wins out, otherwise everything will be placed in an array to execute and the mixin will be pushed first, the component second.

//mixin
const hi = {
mounted() {
console.log('hello from mixin!')
}
}

//vue instance or component
new Vue({
el: '#app',
mixins: [hi],
mounted() {
console.log('hello from Vue instance!')
}
});

output:

> hello from mixin!
> hello from Vue instance!

Conflict

If the two conflict, we can see how the Vue instance or component will win

//mixin
const hi = {
methods: {
sayHello: function() {
console.log('hello from mixin!')
}
},
mounted() {
this.sayHello()
}
}

//vue instance or component
new Vue({
el: '#app',
mixins: [hi],
methods: {
sayHello: function() {
console.log('hello from Vue instance!')
}
},
mounted() {
this.sayHello()
}
})

Output:
> hello from Vue instance!
> hello from Vue instance!

Global Mixins

Global mixins are literally applied to every single component. For this reason, the use case for them is extremely limited and they should be considered with great caution. One use I can think of that makes sense is something like a plugin, where you may need to gain access to everything. But again, even in this instance, I would be wary about what you’re applying, especially when you’re extending functionality to applications that might be a black box for you.

To create a global instance, we would place it above the Vue instance. In a typical Vue-cli build, this would go in your main.js file.

by kushan


avatar
  Subscribe  
Notify of