Recently I needed to add some global functionality to nearly all Vue components in an app. My colleague Seb told me a good way to achieve this: global mixins. In this post I'd like share that knowledge.

In Vue a mixin is some functionality bundled in a file that can be added to one or more Vue components. It's very similar to a trait in PHP.

Let's take a look at how such a regular mixin looks like. It's really nothing more than a .js with some stuff in it. Here's one with a computed property to grab some global info of the current user that has been set on the window object.

export default {
    computed: {
        currentUser() {
            return window.currentUser;
        },
    },
};

If you import and register the mixin you can use it.

<script>
import Auth from './mixins/Auth';

export default {
   mixins: [ Auth ],

   created() {
      // Let's use the function provided by the mixin.
      console.log(`${this.currentUser.name} is currently logged in.`);
   },
}
</script>

Nice. But image now you want to use the same mixin on almost every component in your app. Registering that mixin will grow old pretty fast. Enter global mixins. It's extremely simple. Just register the mixin where you set up Vue. Commenly this would in app.js:

import Vue from 'vue';
import Auth from './mixins/Auth';

Vue.mixin(Auth); 

And with that you can use the functions defined in the mixin in any component:

<script>
export default {
   created() {
      // No need to import the mixin anymore.
      console.log(`${this.currentUser.name} is currently logged in.`);
   },
}
</script>

We can make a small improvement to this. In the Vue world things that are globally accessible (such as this.$set, this.$root, ...) are commonly prefixed with $. We could follow that convention too:

The mixin:

export default {
    computed: {
        $currentUser() {
            return window.currentUser;
        },
    },
};

A component:

<script>
export default {
   created() {
      // so nice
      console.log(`${this.$currentUser.name} is currently logged in.`);
   },
}
</script>

And that's really all there is to it.