Paulund

VueJS - Mixins

Mixins are a way of reusing functionality from within your Vue Components. A mixing will use the same properties as a component such as created, methods and when a component uses this mixin the functions will be merged into the component. If you're coming from a PHP background you can think of mixins as a similar functionality to traits. To show an example of the mixin functionality, we'll create a mixin which will have a message data point, then create 2 components that will reuse this functionality and display the mixin message in different ways. First lets create the HTML for the 2 new components.

<div id="app">
    <mixin-example></mixin-example>
    <second-mixin-example></second-mixin-example>
</div>

First lets create the mixin object, this is just a normal JavaScript object which has a data function that returns an object with a message property telling us the message comes from a mixin.


var mixinExample = {
        data: function(){
            return {
                message: 'This message comes from a mixin'
            }
        },
    };

To use these mixin in our components we need to use the mixins property with a value of an array of our mixins. The template we're using is going to be different on each component so we can see the message is coming from the mixin.

    Vue.component('mixin-example', {
        mixins: [mixinExample],
        template: '<p>First message - {{ message }}</p>'
    });

    Vue.component('second-mixin-example', {
        mixins: [mixinExample],
        template: '<p>Second message - {{ message }}</p>'
    });

With the components setup we simply need to create a new Vue object.


    var app = new Vue({
        el: '#app',
    });

When we load up the page we will see the messages


First message - This message comes from a mixin

Second message - This message comes from a mixin

View the demo to see this in action.

Conflicting Data Points

When you're using mixins it's as if the component is inheriting the properties from the mixin, so what happens if the component has this data point. If there are conflicting data points then the component will use the one defined on it's self, the child will always override the mixin.


    Vue.component('conflicting-mixin-example', {
        mixins: [mixinExample],
        data: function(){
            return {
                message: 'Child component'
            }
        },
    });

When using this component the message will now read as child component.