Vue-mixins mixing process
Vue's mixins are a very flexible way to distribute reusable functionality into Vue components. Mixins are JavaScript objects that can contain any functionality options in a component, such as data, components, methods, created, computed, etc. By passing common functionality into the mixins options as objects, after the component uses the mixins object, the options of the mixins object will be extended to the options of the component itself, thus improving the reusability and maintainability of the code.
The method of use is as follows:
- Create the mixins folder under the src folder and create the JavaScript file in the folder.
- In a JavaScript file, write configuration items for Vue component instances, including data, methods, computed, lifecycle functions, and so on.
- In the Vue file where mixins are required, import the mixins file.
- In the mixins option of the Vue file, by adding the imported mixins object to the array, multiple mixins objects can be mixed, and the later ones have higher priority, overriding the previous ones.
- Now, the data and methods in the mixins file are mixed into the corresponding Vue file, which can be accessed through this.
Notes:
- If the mixins file and the component provide data or methods with the same name, the priority inside the component is higher.
- If a lifecycle function is written, the lifecycle functions in mixins and the lifecycle functions of the page are executed in the order of the array without conflict.
Example code:
// mixins.js
export default {
created() {
console.log('嘎嘎')
},
data() {
return {
title: '标题'
}
},
methods: {
sayHi() {
console.log('你好')
}
}
}
// MyComponent.vue
import mixins from '@/mixins/mixins'
export default {
mixins: [mixins],
// 其他组件选项...
}In the MyComponent component, you can access the mixed data and methods through this.title and this.sayHi ().

简体中文
English
Article comments