<[object Object] defer="true" src="https://static.cloudflareinsights.com/beacon.min.js" token="0a1dcfae6c4348e2aa2d13c20d9fe61d">

# Mixins

These are a way to extend functionality for your components. You can create mixins with component options (ie. the ones from the configuration object) and then mix them with your components so that they gain more features.

TIP

Mixins according to the official guide.

# Syntax

To create a mixin, declaring an object and passing in Vue configuration options will be enough:

let myMixin = {
    created() {
        console.log('hello from created hook!')
    },
    data() {
        return {
            myValue: true // available as `this.myValue` on the component
        }
    },
    methods: {
        myMethod() {
            // available as `this.myMethod()` on the component
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Notice how we have a lifecycle hook, reactive data and methods in that object? All of them will be ... well... mixed in a component if we decided to do the following:



 



new Vue({
    ...
    mixins: [ myMixin ]
    ...
})
1
2
3
4
5

Yup. Once again your instincts are correct and there is a mixins key on the configuration object you can use to get this working. It is an array, which means you can pass in as many mixins as you want in here.

This means that everything from myMixin will be available to the newly created instance.

There are some considerations to make, remember this is a way to merge but not necessarily override the values in your instance. So overlapping options will have merging strategies:

  • For data objects, component's data will take priority in case of conflicts.
  • Lifecycle hook functions will be merged into an array and mixing hooks will run first, then the component's.
  • Other options, like methods or other components will be merged with the receiving component and its properties will take priority over the ones in the mixin.

TIP

Vue also provides the ability to create global mixins as well as setting your own custom merging strategies, but the first are not really recommended and the second I think would be a more advanced use case. We'll see if we need it in the future sections.

# Example

See the Pen 08. Mixins by @ackzell on CodePen.

Last Updated: 9/15/2020, 12:54:52 AM