Pinia w/ Vue3:在模板中使用操作返回 funcName 不是函数

syl*_*man 6 vuejs3 pinia

在 Vue3 中的模板中使用 Pinia 操作可以给出

未捕获的类型错误:$setup.[storeName].[actionName] 不是函数

我做错了什么还是预期的行为?似乎没有其他人有同样的问题。谷歌搜索没有透露任何信息。

我正在使用新组件

Dav*_*les 7

当我错误地尝试用 来解构动作以及状态和吸气剂时,我遇到了这个问题,因为我没有足够仔细地阅读Pinia 文档storeToRefs中的这一点:

\n
\n

为了从存储中提取属性同时保持其反应性,您需要使用storeToRefs(). 它将为每个反应性属性创建引用。当您仅使用存储中的状态而不调用任何操作时,这非常有用。请注意,您可以直接从商店 解构操作[强调],因为它们也绑定到商店本身。

\n
\n

所以给定这个模板 \xe2\x80\x94

\n
<template>\n  <ul>\n    <li v-for="thing in things" :key="thing">{{ frob(thing) }}</li>\n  <li>\n</template>\n
Run Code Online (Sandbox Code Playgroud)\n

\xe2\x80\x94 和这个商店 \xe2\x80\x94

\n
const useStore = defineStore("store", {\n  state: () => ({ things: ["1", "2", "3"], }),\n  actions: { frob(arg) { return `frobbed ${arg}`; } },\n});\nconst store = useStore();\n
Run Code Online (Sandbox Code Playgroud)\n

\xe2\x80\x94 如果你尝试用 来解构和things,你会得到。与状态和 getter 不同,操作应该直接从存储对象中解构:frobstoreToRefsTypeError: $setup.frob is not a function

\n
// wrong\nconst { things, frob } = storeToRefs(store);\n\n// right\nconst { things } = storeToRefs(store)\nconst { frob } = store\n
Run Code Online (Sandbox Code Playgroud)\n

请注意,在 Chrome 中,错误将显示为Uncaught (in promise),而在 Safari 中,错误将显示为Unhandled Promise Rejection

\n