How to use mixins in vue

Refer to the official website and some information on the Internet, the most basic usage

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.
Mixins are to define a part of public methods or calculated properties, and then mix them into various components for use, which can be easily managed and uniformly modified.

common.js file

export const mixin = {
    
    
	data() {
    
    
		return {
    
    
			num: 1
		}
	},
	methods: {
    
    
		fangfa() {
    
    
			console.log('vue中mixins的使用方法')
		}
	}
}

vue file

<script>
import {
    
     mixin } from '../../common/common' //common.js的路径

export default {
    
    
	mixins: [mixin],
	mounted() {
    
    
		this.fangfa()
		console.log('num',this.num)
	}
}
</script>

run
![Insert picture description here](https://img-blog.csdnimg.cn/2020080916362246.png

When a component and a mixin object contain options with the same name, these options will be "merged" in an appropriate way.
For example, the
data objects will be merged recursively internally, and when conflicts occur, the component data
will be given priority. The hook functions of the same name will be merged into an array, so they will all be called. In addition, the hook of the mixed object will be called before the hook of the component itself.
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_43908123/article/details/107895573