官方文檔沒找到具體的例子颓遏,就拼命百度付枫, 終于找到了方法
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 消費(fèi)組件引入
<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類型, 可以接收參數(shù))
//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 封裝引入消費(fèi)組件后狗热,yarn serve的時候钞馁, 會報錯, 報沒有找到getList方法匿刮,因為getList是在消費(fèi)組件中封裝的方法僧凰,mixins/page.js里沒有定義這個方法,這個時候需要傳參
vue3 .vue 消費(fèi)組件引入 (視覺上更直觀熟丸,知道哪些方法或值是從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>