How to use mixins in Vue.js — basic example and applying

Elena Raspopova
2 min readFeb 26, 2021

Using mixins in Vue.js is a way to reuse functionality across different components in your web application.

If you notice that you are copying and pasting the same code block across the multiply components you definitely should use mixins in your web application.

This is a great approach to reduce the number of lines in code make it looks more professional and easier to read.

Let’s see how mixins work in practice.

Mixins are a flexible way to distribute reusable functionalities for Vue components (Official docs).

Basic example

Inside your Vue application we need to create a folder called “mixins”, where we will put files with extension .js.

Here I created formatTime.js file with the function that console current time. Assume that the given functionality might be needed in various components.

Don’t forget export our functionality in a mixin file, in this case formatTime.

In the target component initially we imported the mixin file and declared mixins into an array, like that mixins: [formatTime]. So you can insert several another mixin files.

Now we can use the imported mixin functionality in usual way throughout the current component.

Important to note

It is worth to notice that mixins code runs before a local component code.

And in case if you have conflicting data (for instance the same methods name), the components wins out.

You can also apply mixin globally. But you should use it in caution, because it affects to every Vue components in an application.

Conclusion

Today we introduced the concept of mixins in Vue. With them you can easily stick to the main programming rule — DRY (don’t repeat yourself) and make your code clean and elegant.

--

--