Explain the use of vue mixin in the project

1. What is mixin?

混入 (mixin) It provides a very flexible way , to distribute Vue assembly of reusable functions . A mixin object can contain any component options. When a component uses a mixed-in object, all the options of the mixed-in object will be "mixed" into the options of the component itself.

2. How to use mixins in the project?

In vue components, if you want to reuse some common functions, such as components, methods, hook functions, etc., mixing is a good choice. Here is a brief introduction to the method and characteristics of mixing.
We can create a directory mixinsand create a common.jsfile as shown in the figure:
Insert picture description here

Define the mixin object

common.js is what we want to mix into other components:

export default {
    
    
  data() {
    
    
    return {
    
    }
  },
  created() {
    
     //钩子函数
    console.log('这是混入的组件')
    this.hello();
  },
  methods: {
    
    
    hello() {
    
    
      console.log('hello! 混入test');
    },
  }
}

Use mixins in components

Import the common.js file in the test2.vue file, and use mixins to mix the common.js content into the current component

<template>
  <div>
  </div>
</template>

<script>
import mixinTest from "../../mixins/common.js";
export default {
    
    
  mixins: [mixinTest],
  data() {
    
    
    return {
    
    
      level: "1",
    };
  },
};
</script>

<style lang="scss" scoped>
</style>

effect

Insert picture description here

3. In-depth study of the combination of options

The use of mixin is destined to encounter the problem that the mixin object and the component that uses the mixin object have the same name in the options.

When the component and the mixed-in object contain options with the same name, Vue will appropriately solve the problem by "merging", as follows:

  • Data objects will be merged recursively internally, and component data will take precedence when conflicts occur .
  • The hook functions of the same name will be merged into an array, so all will be called . In addition, the hook of the mixed object will be called before the hook of the component itself. That is: the timing of mixing into the object hook> the component's own hook
  • Options whose values ​​are objects, such as methods, componentsand directives, will be combined into the same object. When the key names of two objects conflict, take the key-value pair of the component object.

4. Matters needing attention

Mixing can also be registered globally. Be extra careful when using it! Once the global mixin is used, it will affect every Vue instance created later.

Please use global mixins with caution, as it will affect every Vue instance created separately ( including third-party components ).

reference

https://blog.csdn.net/weixin_46071217/article/details/108742358

Guess you like

Origin blog.csdn.net/weixin_45844049/article/details/114943184