product_list.ts 1.9 KB
import { getProductList } from './../service'
import { ref, watchEffect } from 'vue'
import { defineStore } from 'pinia'
import type { Product, ProductImage, ProductListQuery } from '@/type'

export const useProductListStore = defineStore('productList', () => {
  const list = ref<Product[]>([])
  const productCategoryId = ref('') // 选中的类别
  const keyword = ref()
  const pageNo = ref(1)
  const pageSize = ref(20)
  const total = ref(0)
  const params = ref()

  const getList = async (params: ProductListQuery) => {
    if (params.productCategoryId || params.keyword) {
      const { data } = await useAsyncData('product', () => $fetch('/shop/product/list', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          ...params,
          pageNo: pageNo.value,
          pageSize: pageSize.value
        })
      }))

      // const data = res.data?.data || {}
      list.value =
        (data.value?.data?.records || []).map((record: Product) => ({
          ...record,
          // http://112.74.45.244:8100/api/show/image?fileKey=ac82abea34243b7f7a56e5c3ca03f3a9
          imgList: JSON.parse(record.productimageliststore as unknown as string).map(
            (item: ProductImage) => ({
              url: `/api/show/image?fileKey=${item.fileKey}&psize=p256`
            })
          )
        })) || []
      total.value = data.value?.data?.total || 0
    }
  }

  const updatePageNo = (value: number) => {
    pageNo.value = value
  }

  const updateCategory = (value: string) => {
    productCategoryId.value = value
  }

  const updateParams = (value: any) => {
    params.value = value
  }

  const updateKeyword = (value: string) => {
    keyword.value = value
  }

  return {
    pageNo,
    pageSize,
    total,
    list,
    keyword,
    params,
    getList,
    updateCategory,
    updatePageNo,
    updateParams,
    updateKeyword
  }
})