官方文档没找到具体的例子,就拼命百度, 终于找到了方法
vue2 mixins封装
export default {
data() {
return {
pageSize: 20,
pageNum: 1,
total: 0,
pageSizes: [10, 20, 50]
}
},
methods: {
handleSizeChange(val) {
this.pageSize = val;
this.handleCurrentChange(1);
},
handleCurrentChange(val) {
this.pageNum = val;
this.getList();
}
}
};
vue2 .vue 消费组件引入
<script>
import pageMix from '@mixins/page';
export default {
mixins: [pageMix],
data() {
return {
data: [],
};
},
methods: {
getList() {
let query = {
pageNum: this.pageNum,
pageSize: this.pageSize,
};
// ajax.xxxxx(query).then((res) => {
// this.data = res;
// this.total = (res || []).length;
// });
},
},
};
</script>
vue3 mixins (返回一个function类型, 可以接收参数)
//mixins/page.js
import { reactive } from "vue"
export default function (getList) {
const stateData = reactive({
pageFilter: {
page: 0,
size: 10,
},
pageConfig: {
loading: false,
pageSizes: [10, 30, 50],
total: 0,
},
})
let handleSizeChange = (val) => {
stateData.pageFilter.page = 0;
stateData.pageFilter.size = val;
getList();
};
let handleCurrentChange = (val = 1) => {
stateData.pageFilter.page = val - 1;
getList();
};
return {
stateData,
handleSizeChange,
handleCurrentChange,
}
}
mixins 封装引入消费组件后,yarn serve的时候, 会报错, 报没有找到getList方法,因为getList是在消费组件中封装的方法,mixins/page.js里没有定义这个方法,这个时候需要传参
vue3 .vue 消费组件引入 (视觉上更直观,知道哪些方法或值是从mixins引入的)
<script>
import pageMix from '../../mixins/page.js';
import { reactive, toRefs } from 'vue';
export default {
setup() {
let state = reactive({
filter: {
keyword:'',
},
data:[],
});
const getList = () => {
let query = Object.assign(
{},
state.filter,
stateData.pageFilter
);
query.keyword = query.keyword.trim();
// ajax.xxxxx(query).then((res) => {
// state.data = res;
// stateData.pageConfig.total = (res || []).length;
// });
};
const { stateData, handleSizeChange, handleCurrentChange, handleDate } =
pageMix(getList); // 将mixins/page.js中要用到的方法传过去
return {
...toRefs(state),
...toRefs(stateData),
handleSizeChange,
handleCurrentChange,
handleDate
};
},
};
</script>
网友评论