SoFunction
Updated on 2025-04-03

Detailed explanation of Mixins mixed use

Mixins generally have two uses:

1. After you have written the constructor, you need to add methods or methods to use temporary activities. Using mixed in will reduce source code pollution.

2. Public methods used in many places. Using mixed methods can reduce the amount of code and realize code reuse.

1. Basic usage of Mixins

We now have a program of increasing numbers. Assuming it has been completed, we hope that every time the data changes, we can print a prompt on the console: "The data has changed."

Code implementation process:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <script type="text/javascript" src="../assets/js/"></script>
  <title>Mixins Option Demo</title>
</head>
<body>
  <h1>Mixins Option Demo</h1>
  <hr>
  <div >
    <p>num:{{ num }}</p>
    <P><button @click="add">Increase the number</button></P>
  </div>
 
  <script type="text/javascript">
    // When additional temporary addition, it is used to display logs    var addLog={
      updated:function(){
        ("Data release changes, changes into"++".");
      }
    }
    var app=new Vue({
      el:'#app',
      data:{
        num:1
      },
      methods:{
        add:function(){
          ++;
        }
      },
      mixins:[addLog]//Mixed in    })
  </script>
</body>
</html>

2. The order of mixins

In terms of execution order, it is mixed with execution first, and then executed in the constructor. It should be noted that this is not a method coverage, but is executed on both sides.

In the constructor of the above code, we also added the updated hook function:

updated:function(){


   ("Updated method in the constructor.")


},

At this time, the order of output of the console is:

The release of mixins data changes, and changes into 2.
The updated method in the constructor.

PS: When the method of mixing inclusion and the method of the constructor is duplicated, the method of mixing inclusion cannot be displayed, which means it does not work.

3. Global API mixing method

We can also define global inclusions, so that we can directly introduce js where this code is needed, and we can have this function. Let's take a look at the global mixing method:

({


  updated:function(){


    ('I was mixed up in the whole world');


  }


})

PS: The execution order of global mixing must be preceded by the mixing and constructor methods.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.