如何在 Vue.js 3 中使用 Pinia 正确处理从 API 获取的信息?

yer*_*rin 10 api vue.js vuejs3 pinia

我目前正在开发一个从 API 获取数据的项目。\n我需要访问我的应用程序中的所有数据,所以我认为最好的选择是使用 Pinia(通常我使用 Vuex,但我想尝试一下)这个“新”商店解决方案)。

\n

我的“问题”是,我真的不知道我实现目标的方式是否是最好的方式,甚至是“良好的做法”。在我的 Pinia 商店里我写了这样的内容:

\n
\nexport const listadoADPs = defineStore("listado", {\n  state: () => ({\n    adps: [],\n  }),\n  actions: {\n    getADPs() {\n      const api =\n        "URL";\n\n      fetch(api)\n        .then((response) => response.json())\n        .then(({ data }) => (this.adps = data))\n        .catch((error) => console.log(error));\n    },\n  },\n});\n
Run Code Online (Sandbox Code Playgroud)\n

然后,在我的组件中我编写了以下代码:

\n
<script setup>\nimport { ref, computed } from "vue";\nimport { listadoADPs } from "@/stores/adps";\nconst store = listadoADPs();\n\nconst cards = ref([\n  {\n    number: computed(() => store.adps.length),\n    description: "ADPs vigentes",\n  },\n  {\n    number: computed(\n      () => store.adps.filter((adp) => adp.estado_cd === "Suscrito").length\n    ),\n    description: "Convenios de Desempe\xc3\xb1o Suscritos",\n  },\n  {\n    number: 0,\n    description: "Alertas enviadas",\n  },\n]);\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n

具体来说,我不知道为数组“cards”中的每个“数字”键创建一个计算属性是否正确,我的意思是,最终是相同的数据,那么为什么我不能只创建一个计算属性并保存变量中的数据?\n问题是,如果我在重新加载页面时以这种方式工作,数据就会消失。

\n

阅读文档和更多内容,我认为存在一个我仍然完全不理解的反应性问题,但我真的很想完善这段代码,所以我更愿意问你。

\n

Luc*_*oke 6

我会在这里使用吸气剂。

\n
// store.ts\nexport const listadoADPs = defineStore("listado", {\n  state: () => ({\n    adps: [],\n  }),\n  actions: {\n    getADPs() {\n      const api =\n        "URL";\n\n      fetch(api)\n        .then((response) => response.json())\n        .then(({ data }) => (this.adps = data))\n        .catch((error) => console.log(error));\n    },\n  },\n  getters: {\n    // BEWARE: getter names cannot be same as state props!\n    listadoADPs(state) {\n      return state.adps.length;\n    },\n    adpsFilteredLength(state) {\n      return (query: string) => state.adps.filter((adp) => adp.estado_cd === query).length;\n    }\n  },\n});\n
Run Code Online (Sandbox Code Playgroud)\n

在你的组件中

\n
<script setup>\nimport { ref, computed } from "vue";\nimport { listadoADPs } from "@/stores/adps";\nconst store = listadoADPs();\n\nconst cards = ref([\n  {\n    number: store.adpsLength,\n    description: "ADPs vigentes",\n  },\n  {\n    number: computed( // must be computed because of sending parameter\n      () => store.adpsFilteredLength("Suscrito")\n    ),\n    description: "Convenios de Desempe\xc3\xb1o Suscritos",\n  },\n  {\n    number: 0,\n    description: "Alertas enviadas",\n  },\n]);\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n

为了持久化,这个 Pinia 插件似乎做得很好:\n https://www.npmjs.com/package/pinia-plugin-persist

\n

正如其他人已经提到的,如果不提供更多信息,我无法为您提供更多帮助。

\n

理想情况下重现您的问题;)

\n