vue2中的mixins
- 其实听起来很小众,但是一旦公共方法很多的时候就会有很大的重复性,这时候就需要用到mixins
- mixins是vue2.0中新增的选项,用来实现代码复用
- mixins中可以定义多个对象,每个对象可以包含多个属性和方法
- mixins中定义的属性和方法,可以全局使用,也可以局部使用
下面利用mixins写一个分页组件:
1. 定义分页的mixins
export default {
data() {
return {
currentPage: 1,
pageSize: 10,
totalItems: 0,
};
},
computed: {
slicedTableData() {
this.loading = false;
const startIndex = (this.currentPage - 1) * this.pageSize;
const endIndex = startIndex + this.pageSize;
return this.tableData.slice(startIndex, endIndex);
},
},
methods: {
handleCurrentChange(val) {
this.currentPage = val;
this.handleTable();
},
handleSizeChange(val) {
this.pageSize = val;
this.currentPage = 1;
this.handleTable();
},
},
};
2. 引入组件
<script>
import paginationMixin from '@/utils/paginationMixin'
export default {
mixins: [paginationMixin],
}
</script>
- 这样只需要在使用到上面mixins方法的时候引入mixins即可,哪里使用哪里引用,无需再写重复方法