category.ts 1.85 KB
import { ref } from "vue";
import { defineStore } from "pinia";
import type { Category, CategoryRootType } from "../type";

export const useCategoryStore = defineStore("category", () => {
  const list = ref<CategoryRootType[]>([]);
  const selectedCategory = ref(""); // 选中的一级类别
  const selectedSubCategory = ref(""); // 选中的二级类别
  const selectedFuncCategory = ref("");
  const categoryVisible = ref(true);
  let resetFuncValue = "";
  let resetCategoryValue = "";

  const getList = async () => {
    const config = useRuntimeConfig();
    // 在SSR中,数据仅在服务器端获取并传递到客户端。
    const { data } = await useAsyncData(
      "category",
      () =>
        $fetch("/shop/product/category", {
          method: "GET",
        }),
      {
        server: true, // 仅在服务器端获取数据
      }
    );

    const rootList = data.value.data.rootCategoryList;
    list.value = rootList || [];
    resetCategoryValue = selectedCategory.value =
      rootList[0].categoryDisplayName;
    selectedSubCategory.value = rootList[0].list[0].id;
    resetFuncValue = selectedFuncCategory.value =
      rootList[0].productFunctions[0].id;
  };

  const updateCategory = (value: string) => {
    selectedCategory.value = value;
    updateFuncCategory(value === resetCategoryValue ? resetFuncValue : "");
  };

  const updateSubCategory = (value: string) => {
    selectedSubCategory.value = value;
  };

  const updateFuncCategory = (value?: string) => {
    selectedFuncCategory.value = value || "";
  };

  const updateDisplay = (visible: boolean) => {
    categoryVisible.value = visible;
  };

  return {
    list,
    selectedCategory,
    selectedSubCategory,
    selectedFuncCategory,
    resetCategoryValue,
    categoryVisible,
    getList,
    updateCategory,
    updateSubCategory,
    updateFuncCategory,
    updateDisplay,
  };
});