将反应性 pinia 状态作为 axios 参数传递的正确方法是什么?

What is the proper way to pass a reactive pinia state as axios params?

我正在尝试为我的 axios 参数使用两个 pinia 存储,但是当我发送 axios 请求时,状态作为一个完整的代理对象发送。

stores/product-filter.js

import { defineStore } from "pinia";

export const useProductFilterStore = defineStore("productFilter", {
  state: () => ({
    id: undefined,
    title: undefined,
    ...
  }),
});

stores/product-pagination.js

import { defineStore } from "pinia";

export const useProductPaginationStore = defineStore("productPagination", {
  state: () => ({
    pagination: {
      page: 1,
      rowsPerPage: 15,
      rowsNumber: false,
    },
  }),
});

stores/product.js

import { defineStore } from "pinia";

import { useProductFilterStore } from "./product-filter";
import { useProductPaginationStore } from "./product-pagination";

const paginationStore = useProductPaginationStore();
const filterStore = useProductFilterStore();

export const useProductStore = defineStore("product", {
  state: () => ({
    products: [],
  }),

  actions: {
    fetchProducts() {
      return axios.get(process.env.API_URL + "product", {
        params: {
          limit: paginationStore.pagination.rowsPerPage,
          page: paginationStore.pagination.page,
          filter: filterStore,
        },
      });
    },
  },
});

所以当我 fetchProducts 我得到整个对象时

limit: 15
page: 1
filter[$id]: productFilter
filter[_isOptionsAPI]: true
filter[router][currentRoute][__v_isShallow]: true
filter[router][currentRoute][dep][w]: 0
filter[router][currentRoute][dep][n]: 0
filter[router][currentRoute][__v_isRef]: true
filter[router][currentRoute][_rawValue][fullPath]: /product
filter[router][currentRoute][_rawValue][hash]: 
filter[router][currentRoute][_rawValue][name]: api.product.index
filter[router][currentRoute][_rawValue][path]: /product
filter[router][currentRoute][_rawValue][matched][][path]: /
filter[router][currentRoute][_rawValue][matched][][name]: api.default

尝试以下方法也不起作用:

...
const { filter } = storeToRefs(filterStore);
...

params: {
  limit: paginationStore.pagination.rowsPerPage,
  page: paginationStore.pagination.page,
  filter: filterStore,
},

(被动地)执行此操作的最佳方法是什么?

stores/product.js 中,您将整个商店传递给 Axios。 看来你只想传递商店的状态,所以试试这个:

fetchProducts() {
  return axios.get(process.env.API_URL + "product", {
    params: {
      limit: paginationStore.pagination.rowsPerPage,
      page: paginationStore.pagination.page,
      filter: filterStore.$state, // This
    },
  });
},

P.S。 Michal Levý 在对您的问题的评论中独立指出了这一点。