If a variable or method is used in multiple pages or the contents of some hooks are the same, mixins can be used to reduce code redundancy. See the use of vue official website
For example, when the background management system is displayed in the form of tables, variables such as pageNo and pageSize of data, as well as the clicking method of the next page and the last page are actually the same. Therefore, we can extract these variables and methods and use mixed methods to avoid repetitive code writing. And convenient later maintenance.
export const pagination = {
data () {
return {
pData: {
currentPage: 1.pageSizes: [10.20.50.100].pageSize: 10.total: 0,}}},methods: {
handleSizeChange(pageSize, callback) {
this.pData.currentPage = 1;
this.pData.pageSize = pageSize;
callback ? callback() : this.getData();
},
handleCurrentChange(currentPage, callback) {
this.pData.currentPage = currentPage;
callback ? callback() : this.getData(); }}}Copy the code
Simple complete example: mixin/common.js:
export const commonModule = {
// You can write any lifecycle hook
data () {
return{}},methods: {
goRoute(routeName,query){
console.log('CommonJS goRoute method for triggering mixin files')
this.$router.push({
name: routeName,
query
})
}
}
}
Copy the code
Use:
<div class="mine elastic-c-c" @click="goRoute('mine')"></div>
import { commonModule } from '@/mixin/common.js'
export default {
mixins: [commonModule]
data(){
return {}
}
}
Copy the code
We found that the route jump operation is used in many pages, so we changed it to global interfuse: main.js
import { commonModule } from '@/mixin/common.js'
Vue.mixin(commonModule)
Copy the code