The use of vue's mixin in project development

As front-end development frameworks become more and more popular, there are various solutions to performance and code redundancy. Among them, reuse is the most core and widely used method. Common Extract some components or data to make them into components.

Vue also provides mixin data mixing. The essence is to extract a part of data or hooks, methods, etc., and then directly mix in the required component page. At this time, the current component has the function of mixing.


Write a commonly used example and create xxx.js mixin in the mixin folder :

export const myMixins = {
    
    
  data() {
    
    
    return {
    
    }     //可以混入重复的数据
  },
  inject: ['Id'],    //vue提供的另外一种数据传递方式,用于父组件向子孙组件传递数据,某些组件嵌套链中都会用到的属性
  computed: {
    
    
    regionId() {
    
    
      return this.Id()    //获取id
    }
  },
  watch: {
    
    
    Id: {
    
    
      handler: function() {
    
    
        this.getData && this.getData()      //只要全局的某个属性变化,那么就自动执行一次更新数据的函数
      },
      immediate: true    //首次进入立即执行一次
    }
  }
}

Inject, provide, and inject appear in pairs (I will write a separate article on this)
Function: used to pass data from parent components to descendant components
Usage method: provide returns the data to be passed to the subordinate in the parent component, and inject is needed Inject data into lower-level components such as descendants or grandchildren that use this data.
Usage scenarios: Since Vue has the $parent attribute, child components can access parent components. But it is more difficult for grandchild components to access ancestor components. Cross-level access to parent component data can be easily achieved through provide/inject

In the component:

import {
    
     myMixins } from '../mixins/xxx'
export default {
    
    
  mixins: [ myMixins ],
  data() {
    
    
  	return {
    
    }
}
methods: {
    
    
    getData() {
    
        //统一对外暴露为getData,这样,mixin就可以统一触发了
      this.xxx()
    },
    async xxx(){
    
    }   //更新数据的方法
}

Guess you like

Origin blog.csdn.net/kirinlau/article/details/127939298