As your project gets bigger, you may find yourself copying and pasting the same code snippet (data, Method, Watcher, etc.) over and over again in similar components. Of course, you could write these separate files (referring to similar components) as a component and customize it with props, but having too many props can be confusing. To avoid this problem, most people simply continue to add duplicate code, even though they feel there is a better solution.

Fortunately, VueJS has given us Mixins — a way to reuse the same code in different components. A Mixin object can use any property of a component (data, Mounted, created, Update, etc.). When a component uses a Mixin, all information about the Mixin is mixed into the component, and the component can access all Mixin properties as if they were declared in its own object. Let’s take an example:

// mixin.js file
export default {
   data () {
      msg: 'Hello World'
   },
   created: function () {
      console.log('Printing from the Mixin')},methods: {
      displayMessage: function () {
         console.log('Now printing from a mixin function')}}}// -----------------------------------------------------------
// main.js file
import mixin from './mixin.js'
new Vue({
   mixins: [mixin],
   created: function () {
      console.log(this.$data)
      this.displayMessage()
   }
})
// => "Printing from the Mixin"
// => {msg: 'Hello World'}
// => "Now printing from a mixin function"
Copy the code

You can see that when a mixin is used, the component contains all of the mixin’s data and can be accessed using this. You can also define mixins in a variable instead of a file. Frankly, that’s pretty much all there is to mixin, but I thought it would be useful to know about some extreme situations.

What happens when names conflict?

Naming conflicts occur when a property in a mixin has the same name as a property in a component. When this happens (except for life cycle functions), properties in the component take precedence. For example, if you have a title variable in both the component and the mixin — this.title returns the title in the component. The code is as follows:

// mixin.js file
export default {
   data () {
      title: 'Mixin'}}// -----------------------------------------------------------

// main.js file
import mixin from './mixin.js'
export default {
   mixins: [mixin],
   data () {
      title: 'Component'
   },
   created: function () {
      console.log(this.title)
   }
}
// => "Component"
Copy the code

Ok, almost there…

Of course there is more to learn about Vue mixins, but this is enough to get you started and cover most usage situations. If you want to learn more about advanced content, such as global mixins and merging strategies, check out the mixins documentation. I like the Vue documentation, I think it’s well written and easy to understand.

Mixing is welcome!

The original