vue——Extract public code and mix it into mixin

Mixin provides a very flexible way to distribute reusable functions in Vue components. 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.

PS: Simply put, the public properties or method functions reused by multiple components are defined in a single js file and can be introduced in the component used.

Define the mixin.js file

	export default{
    
    
		data(){
    
    
			return {
    
    
				username:'',
				city:''
			}
		},
		methods:{
    
    
			add(){
    
    
				
			}
		},
		mounted() {
    
    
			
		}
	}

Use within the component

import mixin from './mixin.js'

export default{
    
    
	mixins:[mixin],

}

When the mix-in conflicts with the attribute or method of the same name in the component: the data method is the component first, the hook function will be executed, and the mixed-in will be executed first

  1. Data objects will be merged recursively internally, and component data will take precedence when conflicts occur.
  2. The hook functions of the same name will be merged into an array and will be called. The hook of the mixed object will be called before the hook of the component itself.
  3. Options whose values ​​are objects, such as methods, components, and 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.

Guess you like

Origin blog.csdn.net/weixin_51198863/article/details/114081504