Tell me about your understanding of Vue's mixin, what are the application scenarios?

What are the application scenarios for the understanding of Vue's mixin?

what is mixin

official definition

mixin(mixins), which provide a very flexible way to distribute reusable functionality in Vuecomponents .

The essence is actually an jsobject, which can contain any function options in our components, such as data, components, methods, created, computedetc.

We only need to pass the common function into mixinsthe option , and when the component uses mixinsthe object, the options of all mixinsobjects will be mixed into the options of the component itself.

Precautions

When the component has mixinthe same options as the object, the option of the component will be overwritten when the recursive merge is mixinperformed

But if the same option is a life cycle hook, it will be merged into an array, the hook will be executed first mixin, and then the hook of the component will be executed

scenes to be used

In daily development, we often encounter the same or similar codes that need to be used in different components, and the functions of these codes are relatively independent

VueAt this time, mixinthe same or similar code can be proposed through the function

example

Define a modalpop-up window component, which is used isShowingto control the display internally

const Modal = {
  template: '#modal',
  data() {
    return {
      isShowing: false
    }
  },
  methods: {
    toggleShow() {
      this.isShowing = !this.isShowing;
    }
  }
}

Define a tooltipprompt box, which is internally isShowingcontrolled by

const Tooltip = {
  template: '#tooltip',
  data() {
    return {
      isShowing: false
    }
  },
  methods: {
    toggleShow() {
      this.isShowing = !this.isShowing;
    }
  }
}

By observing the above two components, it is found that the logic of the two is the same, and the code control display is also the same, which mixinwill come in handy at this time

First extract the common code, write amixin

const toggle = {
  data() {
    return {
      isShowing: false
    }
  },
  methods: {
    toggleShow() {
      this.isShowing = !this.isShowing;
    }
  }
}

In use of the two components, only need to introducemixin

const Modal = {
    
    
  template: '#modal',
  mixins: [toggle]
};
 
const Tooltip = {
    
    
  template: '#tooltip',
  mixins: [toggle]
}

Through the above small example, let us know that Mixinit is so interesting, convenient and practical to encapsulate some reusable functions

Guess you like

Origin blog.csdn.net/weixin_50975172/article/details/130933258