Mixins: Some valuable understandings in Vue JS

Mixins are certainly a flexible way to distribute reusable functionalities for Vue components. And so, a mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options. All in all, these modules are useful for writing in a functional style. Because ultimately, functional programming is about making code understandable by reducing moving parts.

Vue mixins: Some knowledge you might need to know
Vue mixins: Some knowledge you might need to know

A mixin allows you to encapsulate one piece of functionality so that you can use it in different components throughout the application. As a result, if written correctly, you will reliably always receive the same value with the same inputs. This can be really powerful when it comes to software development. So now, we – ArrowHiTech would like to show you guys some valuable understandings that you should know about Mixins in Vue JS.

But first, let’s go through some definitions.

What are Mixins?

These components that situated in Vue JS are basically a chunk of defined logic, stored in a particular prescribed way by Vue, which can be reused over and over to add functionality to your Vue instances and components. So this kind of component can be shared between multiple Vue components without the need to repeat code blocks. Anyone who has used the CSS pre-processor called SASS obviously has a good idea of mixins.

Example of Mixins

 <html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "databinding"></div>
      <script type = "text/javascript">
         var vm = new Vue({
            el: '#databinding',
            data: {
            },
            methods : {
            },
         });
         var myMixin = {
            created: function () {
               this.startmixin()
            },
            methods: {
               startmixin: function () {
                  alert("Welcome  to mixin example");
               }
            }
         };
         var Component = Vue.extend({
            mixins: [myMixin]
         })
         var component = new Component();
      </script>
   </body>
</html>

So why are these modules important?

Why are mixins important?
Why are mixins important?
  • Firstly, with Vue mixins, you can easily adhere to the DRY principle in programming which simply ensures that you do not repeat yourself.
  • Secondly, by having these modules for your site, you also get a great option of flexibility. A mixin object contains options for Vue components so there is a mixing of both mixin and component options.
  • What’s more, Vue mixins are safe, they do not affect changes outside their defined scope if they are well written.
  • Finally, they are a great platform for code reusability.

How can these modules solve problems in Vue?

To clarify, one way to fully understand the importance of mixins in Vue is to see the re-use problem in action. So, if you have two components that contain a method that does exactly the same thing or performs the exact functionality in the two components like the simple like this:

Navigate into the project folder and to the src folder and create a components directory where you can then create two components: Test.vue and Modal.vue. Then, copy the code below to the appropriate components respectively.

 // Component 1
// src/components/Test.vue
<template>
  <div>
    <button v-on:click="clicked('you just clicked on button  1')">
      Button 1
    </button>
  </div>
</template>;
export default {
  name: "Test",
  methods: {
    clicked(value) {
      alert(value);
    }
  }
};

The mixins’ component above displays a button that shows an alert modal when clicked. Also, the second component below does exactly the same thing:

 // Component 2
// src/components/Modal.vue
<template>
  <div>
    <button v-on:click="clicked('you just clicked on button  2')">
      Button 2
    </button>
  </div>
</template>;

export default {
  name: "Modal",
  methods: {
    clicked(value) {
      alert(value);
    }
  }
};

Your App.vue file should have both the components imported and declared exactly like it is below. So, you can clearly see that we are repeating the click method code block in both the components. Also, this is not very ideal as it is not an efficient way to handle memory resources. And, it also goes against the DRY principle:

 <template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <Test />
    <modal />
  </div>
</template>;
<script>
import Test from "./components/Test.vue";
import Modal from "./components/Modal.vue";
export default {
  name: "app",
  components: {
    Test,
    Modal
  }
};
</script>

Global mixins

When we use the term global in reference to mixins, we are not referring to being able to access them on every component, like we are with something like filters. Instead, we can already access our modules in a component with mixins: (toggle).

Access the Mixins module when using the component
Access the Mixins module when using the component

Global mixins are certainly applied to every single component. For this reason, the use case for them is extremely limited and they should be considered with great caution. One use that makes sense is something like a plugin, where you may need to gain access to everything instead. But again, even in this instance, it’s still blackout about what you’re applying, especially when you’re extending functionality to anonymous applications.

The use of these in-house components for Vue.js

You can set up your directory structure any way that you like, but we like to create a mixin directory in order to stay organized. The file we’d create would have a .js extension (as opposed to .vue, like our other files), and so, we’d export an object for the mixin. And then in Modal.vue we would now have access to it by importing the toggle like this:

 import Child from './Child'
import { toggle } from './mixins/toggle'

export default {
  name: 'modal',
  mixins: [toggle],
  components: {
    appChild: Child
  }
}

It’s important to understand that though we’re using an object, lifecycle methods are still available to us. We could also hook into mounted() here and it would be applied to the component’s lifecycle. As a result, this makes this way of working really flexible and powerful.

Final words

That should be it! Here are some valuable understandings that you should know when it comes to the term of mixins. To conclude, these modules can be useful to encapsulate a small piece of functionality that you’d like to reuse. They are certainly not the only option available to you: higher-order components, for example, allow you to compose similar functionality. And certainly, this is just one way of working.

We – ArrowHiTech is proud to be one of the most well-established outsourcing companies all around the world. That is to say, with over 12 years of experience, we can provide the best software development services for your eCommerce business. So, you can check us out now: ArrowHiTech services. Also, if you want to go through our showcase, you should visit our product page here: MageSolution or our portfolio: ArrowHiTech portfolio.

ArrowHiTech services

So, if you have any questions, don’t hesitate to contact us via email support@arrowhitech.com or our phone number +84 243 7955 813. We would love to hear every feedback from you guys.