This is the 9th day of my participation in Gwen Challenge

Mixins: is a very flexible way to distribute reusable functionality in Vue components. Mixin objects can contain any component option. When a component uses a mixin object, all mixin options are mixed with the component’s own options.

How do you use it? Here’s an example:

  • Defines a mixin.js object, that is, a JS file
let mixin={
    data(){
        return{
            msg:1}},methods: {foo(){
            console.log('hello from mixin!----'+this.msg++)
        }
    }
}

Copy the code
  • Introduce mixin objects into the required VUE file
<template> <! -- You can use mixed methods.<div @click="foo()">component</div>
</template>
<script>
import mixin from './mixin.js'
export default {
    mixins: [mixin],
    
}
</script>
Copy the code

Very simple to use!

Mixins are characterized by: 1. Methods and parameters are not shared among components. 2. Method override. Methods in mixins are overwritten if the same method is defined repeatedly in the component while referring to the mixins. 3, merge life cycle, JS file life cycle first, component execution later.

Differences between Mixins and 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.

Differences between Minxins and public 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.

Mixins: merge the objects and methods of the component after introducing the component, which extends the objects and methods of the parent component, and can be understood as forming a new component.

Minxins application scenarios:

Vue mixins can be used for encapsulating calls and inheritance when multiple components need to be pulled down to refresh, or when using a single method.