Mixing Vue.mixin

When two or more components have the same attribute or method, extract the same feature and write it into a mixin.jsfile. mixin.jsThe content of the file is the same part of multiple components, and its content is the same as the content of the configuration item of the component. But mixin.jsthe configuration items in the file are all the same.
When a component needs to use mixin.jsthe contents of the file, first import the file in this component mixin.js, and then mixindeclare it as an array in the attribute, and when there are overlapping configuration items, the original configuration items will be retained, and other All are mixed with the original configuration items to form new configuration items. Note: If life cycle functions overlap, they must be executed, not specific components! ! !
How to use:

  • (1) Step 1: Define the configuration items to be mixed:
{
    
    
	data(){
    
    }
	methosds:{
    
    }
}
  • Step 2: Use blending, which includes two ways of global blending and local blending:

    import XXX from module
    global mixin: Vue.mixin(xxx)
    local mixin: minxins:['XXX']

案列:
(1). First define the configuration item mixin.js to be mixed:

export const hehe = {
    
    
    methods: {
    
    
        showName() {
    
    
            console.log(this.name);
        }
    },
    mounted() {
    
    
        console.log('a')
    }
}

(2) Import mixin.js in the Student and School components and use them locally:

import {
    
     hehe } from "../mixin";
export default {
    
    
  name: "School",
  data() {
    
    
    return {
    
    
      name: "学校名",
      address: "学校地址",
    };
  },
  mixins: [hehe],
};

Guess you like

Origin blog.csdn.net/qq_45801179/article/details/128494282