How to work with mixins on Vue.js

How to work with mixins on Vue.js

When a component uses a mixin, all options in the mixin will be “mixed” into the component's own options.Mixins in Vue JS are basically a chunk of defined logic, stored in a particular prescribed way by Vue, which can be re-used over and over to add functionality to your Vue instances and components.

What are Mixins?

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

Before you start

This post is suited for intermediate frontend developers that use Vue JS, and so being conversant with beginner concepts and installation processes is assumed. Here are a few prerequisites you should already have before you start to use Vue CLI 3 through this article.

You will need:

  • Node.js 10.x and above installed. You can verify if you do by running node -v in your terminal/command prompt.
  • The Node Package Manager 6.7 or above (NPM) also installed.
  • A code editor: Visual Studio Code is highly recommended. (here’s why)
  • Vue latest version installed globally on your machine.
  • Vue CLI 3.0 installed on your machine. To do this, uninstall the old CLI version first:
npm uninstall -g vue-cli

then install the new one:

npm install -g @vue/cli

OR

  • Download a Vue starter project here

viclotana/vue-canvas

  • Unzip the downloaded project
  • Navigate into the unzipped file and run the command to keep all the dependencies up-to-date:
npm install

Why are Mixins important

  1. With Vue mixins, you can easily adhere to the DRY principle in programming which simply ensures that you do not repeat yourself.
  2. With Vue mixins, 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.
  3. Vue mixins are also safe, they do not affect changes outside their defined scope if they are well written.
  4. They are a great platform for code reusability.

Mixins are a flexible way to distribute reusable functionalities for Vue components.

The problem mixins help to solve

One way to fully understand the importance of mixins in Vue is to see the re-use problem in action. If you have two components that contains a method that does exactly the same thing or performs the exact functionality in the two components like the simple example below:

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. 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);
    }
  }
};

Modal.vue

The component above displays a button that shows an alert modal when clicked. 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);
    }
  }
};

Modal1.vue

Your App.vue file should have the both components imported and declared exactly like it is below:

<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>

App.vue

So you can clearly see that we are repeating the click method code block in the both components and this is not very ideal as it is not an efficient way to handle memory resources and it also goes against the DRY principle.

Introducing Vue Mixins

The team at Vue has now introduced the mixins as a good solution to this problem, with mixins you can encapsulate a piece of code or functionality and then import it for use as often as you want in various components.

Mixin syntax

Vue Mixin from definition to usage looks like this:

// define a mixin object
var myMixin = {
  created: function() {
    this.hello();
  },
  methods: {
    hello: function() {
      console.log("hello from mixin!");
    }
  }
};
// define a component that uses this mixin
var Component = Vue.extend({
  mixins: [myMixin]
});
var component = new Component(); // => "hello from mixin!"

syntax.vue

Demo

You are going to use Vue mixins to rebuild the two components we initially used at the beginning of this post to illustrate the problem. To use mixins in a Vue application, you have to pass through four stages:

  • Create the mixin file.
  • Import the mixin file into the needed component.
  • Remove the repeated logic from said components.
  • Register the mixin.

Creating the mixin file

A mixin file is an exportable javascript file in which the block of code or functionality to be imported and re-used in your various desired Vue components is defined. For developers like myself who like to keep things very modular, create a Mixins folder inside the src folder and then create a clickMixin.js file inside it. Copy the code below into the newly created file.

// src/mixins/clickMixin.js
export default {
  methods: {
    clicked(value) {
      alert(value);
    }
  }
};

clickMixin.js

This is the the mixin file, inside is a simple click method that pops up an alert modal. It can be any logic at all, it can have data options, computed properties and anything a Vue component can have. The possibilities are really only limited to your imagination and use case as a developer.

Importing the mixin file into components

Now that a mixin has been created, the next step is to inject it inside the components where it is needed: where the functionality should come to play. In our demonstration above, that would be inside the two components we already created in the beginning of this post. Import the clickMixin inside the two components with the command below:

import clickMixin from ‘../Mixins/clickMixin’

Removing repeated logic

After importing the mixin, you have to remove the logic you had initially as it is now being taken care of by the mixin. In our case, this means that you will delete the method creation logic in the both components.

// remove this code block and the comma before it.
methods: {
 clicked(value){
  alert(value);
  }
}

Register the mixin

This is where you tell the Vue application that what you imported is a mixin and so it should treat the logic inside it as one and do the dirty work of ensuring the application fixes the functionality and the method calls at the appropriate places in the component. Mixins in Vue by default are registered as arrays like it is below:

<script>
import clickMixin from '../Mixins/clickMixin'
export default {
 name: 'Test',
 mixins: [clickMixin]
}
</script>

register.vue

If you followed through from the start, your application components should be like it is below:

Test.vue

<template>
  <div>
    <button v-on:click="clicked('you just clicked on button 1')">
      Button 1
    </button>
  </div>
</template>;
<script>
import clickMixin from "../Mixins/clickMixin";
export default {
  name: "Test",
  mixins: [clickMixin]
};
</script>

testt.vue

Modal.vue

<template>
  <div>
    <button v-on:click="clicked('you just clicked on button 2')">
      Button 2
    </button>
  </div>
</template>;
<script>
import clickMixin from "../Mixins/clickMixin";
export default {
  name: "Modal",
  mixins: [clickMixin]
};
</script>

modal2.vue

App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <Test msg="Welcome to Your Vue.js App" />
    <modal />
  </div>
</template>;
<script>
import Test from "./components/Test.vue";
import Modal from "./components/Modal.vue";
export default {
  name: "app",
  components: {
    Test,
    Modal
  }
};
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
button {
background-color: #10776e; /* Green */
border: none;
margin: 5px;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
</style>

app1.vue

Types of Mixins

There are two types of mixins in Vue:

  1. Local Mixins: This is the type we have treated throughout this post. It is scoped to the component it is imported into and registered in. The powers of the local mixin is bound by the component it is imported in.
  2. Global Mixins: This is a different type of mixin that is defined in the Main.js file of any Vue project. It affects all Vue components in an application so the Vue team advises that it be used with caution. A definition of a global mixin looks like this:
Vue.mixin({
  mounted() {
    console.log("hello world!");
  }
});

global.js

Important things to note

In the hierarchy of things in a Vue application, inside a component mixins are applied first by default. The component is applied second, so that it can override the mixin in any case. So it is important to always remember that when there is a kind of conflict of authority, the Vue component will always have the final say and overriding powers.

Conclusion

You have been introduced to the concept of mixins in Vue, the types and how they are used with a sample demonstration. It is important you also remember to stick to local mixins and only use global mixins in rare cases when you really need it. Happy coding!

vuejs javascript mixins

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Dedicated VueJS Developers

Want to Hire VueJS Developer to develop an amazing app? **[Hire Dedicated VueJS Developers](https://hourlydeveloper.io/hire-dedicated-vue-js-developer/ "Hire Dedicated VueJS Developers")** on the contract (time/project) basis providing regular...

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

What is ECMAScript and How is it Different From JavaScript?

Many times developers use JavaScript and ECMAScript synonymously for each other. Though they are very closely linked to each other, it does not mean they are the same thing.here is a complete story on the history of JavaScript and how it came into existence. To cut the long story short, ECMA in ECMAScript refers to Europen Computer Manufacturers Association to which JavaScript 1.1 was submitted for standardization back in the year 1997.

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.