The reason for mixins?

We are in the process of development of components, often encounter some components with the same logic and function, if each component of each write a set of methods can lead to redundant code, and later the time change is a change is very waste of time and energy, so you need to put these more abstract the same logic, only need to introduce the components, can achieve a writing code, Multicomponent reuse is where mixins come in.

What are mixins?

Mixins provide a very flexible way to distribute reusable functionality in Vue components. A mixin object can contain any component option. When a component uses mixin, all mixin options are “blended” into the component’s own options.

A mixin can be simply understood as a plain JS file.

Example:

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

Mixins are different from mixins

mixin

Mixins are used for global mixins that affect each component instance and are typically initialized this way by plug-ins. Use with extreme care! Once global mixin is used, it affects every subsequent Vue instance created. When used appropriately, this can be used to inject processing logic for custom options

// Inject a handler for the custom option 'myOption'. Vue.mixin({ created: If (myOption) {console.log(myOption)} function () {var myOption = this.$options.myOption // If (myOption) {console.log(myOption)} } }) new Vue({ myOption: 'hello! ' }) // => "hello!"Copy the code

Pay attention to

Be careful with global mixin, as it affects each individually created Vue instance (including third-party components). In most cases, this should only apply to custom options, as in the example above.

mixins

Component mixin separately, that is, local mixin. This is the most common way to extend components. If you have the same business logic in multiple components, you can strip that logic out and mix it into your code through mixins.

How are mixins used

  1. Use a JS file to extract the script part of vue as follows
  2. In the component where mixins need to be introduced

Here’s an example:

// common.js export default { data(){ return {} }, methods:{}, computed:{}, filters:{}, created(){}, Mounted (){console.log(" I am a mixins"); Vue component <template> <div class="wrapper"> learn mixin </div> </template> <script> import common from '@/mixin/common.js' export default {mixins: [common], Mounted (){console.log(' I am the current component '); }} </script> // Output I am mixins I am the current componentCopy the code

Option to merge

When component and mixin objects have options with the same name, those options are “merged” in the appropriate way, for example, the data objects are internally recursively merged and the component data takes precedence in the event of a conflict.

var mixin = {
  data: function () {
    return {
      message: 'hello',
      foo: 'abc'
    }
  }
}
​
new Vue({
  mixins: [mixin],
  data: function () {
    return {
      message: 'goodbye',
      bar: 'def'
    }
  },
  created: function () {
    console.log(this.$data)
    // => { message: "goodbye", foo: "abc", bar: "def" }
  }
})
Copy the code

The hook function of the same name will be merged into an array, so both will be called. In addition, hooks mixed in with objects are called before the component’s own hooks

Var mixin = {created: function () {console.log(' mixins: [mixin] ')}} new Vue({mixins: [mixin], created: The function () {the console. The log (' component hook is called ')}}) / / = > "mixed with objects of the hook is called" / / = > "component hook is called"Copy the code

Options that are values for objects, such as Methods, Components, and directives, will be combined into the same object. When two object key names conflict, the component object’s key-value pair is taken

var mixin = {
  methods: {
    poo: function () {
      console.log('poo')
    },
    conflicting: function () {
      console.log('from mixin')
    }
  }
}
​
var vm = new Vue({
  mixins: [mixin],
  methods: {
    far: function () {
      console.log('far')
    },
    conflicting: function () {
      console.log('from self')
    }
  }
})
​
vm.foo() // => "poo"
vm.bar() // => "far"
vm.conflicting() // => "from self"
Copy the code

Note: Vue.extend() is also merged using the same strategy

Summary of mixins merge rules

  1. If it is the return value object of the data function

    • Return value objects are merged by default
    • If the properties of the Data return value object conflict, the component’s own data is retained
  2. Lifecycle hook function merge

    • The lifecycle hook functions will be merged into the array and will be called
    • Execute the logic in the Mixin first, and the logic in the execution component for the lifecycle hooks
  3. Options that are values for objects, such as Methods, Components, and directives, will be combined into the same object

    • For example, if both have the methods option and both have methods defined, they will all work
    • But if the key of the object is the same, the key-value pair of the component object is taken

Some features of mixins

  1. The life cycle in a mixins is called in conjunction with the life cycle of the component that introduced the mixins

  2. The component’s data, methods, and filters will override the mixins’ data, methods, and filters of the same name

    For example, methods,components, etc., are merged, and components with conflicting keys will overwrite the blended object. For example, there is A method A in the blended object, and there is also A method A in the component. In this case, the call from the component will execute the method A in the component

  3. The value is the option of the function, the method of the same name in different mixins, in the order introduced, the last overrides the previous method of the same name

    Example created,mounted, etc. A created or mounted hook function is called by merge. A created or Mounted hook function is called before a created or Mounted hook function

  4. Methods and parameters are not shared among components

    If there is A variable cont:1 in the mixed object, change the cont value to 5 in component A, then obtain this value in component B, and get 1 again, and the initial value in the mixed object. Data is not shared

  5. Difference from Vuex

    Vuex: Used for state management. Variables defined in vuEX can be used and modified in each component. After changing the value of a variable in any component, the value of a variable in other components will also be modified

    Mixins: Common variables can be defined and used in each component. Once introduced into the component, the variables are independent of each other and value changes do not affect each other in the component

  6. Differences from common components

    Component: Introducing a component in the parent is equivalent to giving the parent an independent space for the child component to use, and then passing values according to the props, but essentially the two are relatively independent

The disadvantage of mixins

  1. Variable sources are unclear (passed in implicitly) : Unreadable, making code difficult to maintain

    Components can introduce multiple mixins and implicitly call variables/methods directly from mixins, which sometimes leads to confusion about which mixins these variables/methods belong to

  2. Attribute naming conflicts: The life cycles of multiple mixins run together, but attributes and methods with the same name do not merge and may result in conflicts

    For example, if the method in component 1 outputs the property info, but component 2 overwrites the property INFO in component 1, then executing the method in component 1 outputs the property in component 2. This can be avoided, but it can easily lead to conflicts and confusion

  3. High complexity: Mixins and components can have a many-to-many relationship (that is, one component can reference multiple mixins, and one mixins can be referenced by multiple components)

  4. Don’t easily reuse code