You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

51 lines
1.3 KiB

import { loadProductAPI } from "../services/products";
import { ref } from "vue";
/**
* 返回商品接口的数据
* @param {*} categoryId 当前的商品分类id, 空表示获取所有分类
* @returns
*/
export const useProducts = (categoryId = "") => {
const page = ref(1); // 当前页码
const loading = ref(false); // 是否在加载中
const finished = ref(false); // 是否加载完成
const currentCategoryId = ref(categoryId); // 当前分类id
const products = ref([]); // 商品数据
/**
* 加载products
* @param {*} needReset 是否需要重置products
* @param {*} categoryId 分类id
*/
const onLoad = (needReset = false, categoryId = "") => {
if (needReset) {
// 重置一些参数
finished.value = false;
products.value = [];
page.value = 1;
}
// 分类id不为空才需要修改
if (categoryId !== "") {
currentCategoryId.value = categoryId;
}
loading.value = true; // 开始加载
loadProductAPI(page.value, currentCategoryId.value).then((res) => {
finished.value = page.value > res.pages; // 当前页码超过总页数时表示加载完成
loading.value = false;
// 将获取的数据存入products
products.value.push(...res.data);
page.value++; // 页码+1
});
};
return {
// page,
loading,
finished,
products,
currentCategoryId,
onLoad,
};
};