• Understanding Mixins in Vue JS
  • Nwose Lotanna
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: MacTavish Lee
  • Proofread by: Baddyo, Jilanlan

This article is a practical introduction to Mixins in Vue, exploring why Mixins are important and how they can be used in a workflow.

What are Mixins?

Mixins in Vue JS are basically a place to define a bunch of logic, stored in a special way specified by Vue, that can be used over and over again to add functionality to Vue instances and components. As a result, Vue mixins can be shared across multiple Vue components without the need to repeatedly write blocks of code. If you’ve ever used Sass, a CSS preprocessor, then you have a good idea of mixins.

Write it before you start

This article is intended for intermediate front-end engineers developing with Vue JS, so familiarize yourself with the basic concepts and installation process. Before you start using Vue CLI 3, you have these basics in mind.

You need to:

  • Node.js 10.x or later is installed. You can verify your version by running Node -V on your terminal.
  • Node Package Manager version 6.7 or later (NPM) has been installed.
  • A Code editor: Visual Studio Code is highly recommended. (Reasons for recommendation)
  • The latest version of Vue is installed globally on your device.
  • Vue CLI 3.0 is installed on your device. Before installing 3.0, uninstall the CLI tool of the previous version:
npm uninstall -g vue-cli
Copy the code

Then install the new version:

npm install -g @vue/cli
Copy the code

or

  • Download a Vue startup project here:

viclotana/vue-canvas: an optimized, out-of-the-box Vue application with default Babel and ESlint configurations

  • Unzip the downloaded project
  • Enter the decompressed file and run the following command to ensure all dependencies are up to date:
npm install
Copy the code

Why are Mixins important

  1. With Vue Mixins, you can easily follow the DRY principle in your programming, which ensures that you Don’t Repeat your code.
  2. You can also be very flexible with Vue mixins. A mixins object contains options for Vue components, so mixins can be mixed with components.
  3. Vue mixins are also safe, and if you write them properly, they won’t affect changes that go beyond the definition.
  4. They are great platforms for code reuse.

Mixins have the flexibility to distribute reusable functionality to Vue components. – Official documents

What problems have Mixins helped us solve

One way to fully appreciate the importance of mixins in Vue is to look at the reuse issues encountered in real development. If you have two components, each has a method with the same purpose or function, as in this simple example:

After entering your project folder, go to the SRC folder and create a directory named Components and create two components in it: test. vue and modal. vue. Copy the following code into your component.

// 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); }}};Copy the code

The component above shows a button that will bring up an alert box when clicked. The second component 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); }}};Copy the code

Your app.vue file should introduce and declare two components, as follows:

<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>
Copy the code

As you can clearly see from this point, the click-method code in both components is duplicated, and it is not perfect because it wastes memory resources and violates the DRY principle.

Introduce the Vue Mixins

The Vue team has now identified mixins as a great solution to this problem, where you can encapsulate a piece of code or functionality that you can then introduce into various components as needed.

Mixins grammar

From the definition to the use of Vue mixins, the following is the way:

Var myMixin = {created: function() {this.hello(); }, methods: { hello: function() { console.log("hello from mixin!" ); }}}; // Define a Component to use this mixin var Component = vue.extend ({mixins: [myMixin]}); var component = new Component(); // => "hello from mixin!"Copy the code

Demo

Now you can use Vue mixins to refactor the two components used above to illustrate the reuse problem. To use mixins in a Vue application, there are four steps:

  • Caught a file mixed in.
  • Introduce mixin files into the required components.
  • Remove duplicate logic from components.
  • Registered a mixin.

Create mixin files

A mixin file is an exportable JavaScript file that internally defines code blocks and feature blocks that need to be imported and reused in the desired Vue components. For developers like me who like to keep their programming very modular, create a ClickMixin.js file internally after creating a Mixins folder in the SRC folder. Copy the following code in the newly created file:

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

This is a mixin file that contains a simple point-and-click method to implement the pop-up warning box. It can be any logic, it can have data options, calculation properties, and anything else a Vue component can have. Its possibilities are limited to your imagination and the developer’s use case.

Import the mixin file in the component

Now that a mixin has been created, the next step is to inject it into the component that needs it — the component that needs the pop-up warning box functionality. In our demonstration above, the place to insert mixins is inside the two components created at the beginning of this article. Use the following code to introduce clickMixin in both components.

The import clickMixin from '.. Mixins/clickMixin 'Copy the code

Remove repetitive logic

After introducing mixins, you remove the logical code that will be replaced by mixins. In our case, this means that you remove the method creation logic in both components.

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

Registered a mixin

In this step, you tell the Vue application that you are importing mixins, and it treats the logic as unified and performs complex operations to ensure that the application’s fixes and methods are called at the appropriate locations of the component. By default, Mixins in Vue are registered as an array, as shown below:

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

If you had followed my lead from the start, your application component would look something like this:

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>Copy the code

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>Copy the code

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>

Copy the code

The type of Mixins

There are two types of mixins in Vue:

  1. Local Mixins: This is the type we are dealing with in this article. Its scope is limited to imported and registered components only. The scope of influence of a local mixin is determined by the component that introduces it.
  2. Global Mixins: This is a different kind of mixin that is defined in the main.js file in any Vue project. It affects all components in an application, so the Vue development team recommends caution. The definition of a global mixin looks like this:
Vue.mixin({
  mounted() {
    console.log("hello world!"); }});Copy the code

noted

In the transaction layer structure of a Vue application, mixins should take precedence within components by default. Components are applied in the next order so that it can override mixins in any case. Therefore, it is important to remember that the Vue component has final interpretation and override rights in the event of any kind of permission conflict.

conclusion

Using a simple example, this article introduced the concepts, types, and usage of Vue mixins. It is also important to stick with local mixins and use global mixins only in the rare cases where they are necessary. Happy coding!

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.