【问题标题】:Pinia w/ Vue3: Using Actions in template returns funcName is not a functionPinia with/ Vue 3:在模板中使用 Actions 返回 funcName 不是函数
【发布时间】:2022-04-28 05:04:36
【问题描述】:

在 Vue3 的模板中使用 Pinia 动作会给出

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

我做错了什么还是预期的行为。似乎没有其他人有同样的问题。 Google 搜索没有显示任何内容。

我正在使用新组件

【问题讨论】:

  • 遇到了同样的问题。我第一次使用松果
  • 控制 + R 应该可以工作。保存时未加载更改时可能发生

标签: vuejs3 pinia


【解决方案1】:

当我错误地尝试使用storeToRefs 解构动作以及状态和吸气剂时,我遇到了这个问题,因为我没有足够仔细地阅读the Pinia docs 的这段代码:

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

所以给定这个模板——

<template>
  <ul>
    <li v-for="thing in things" :key="thing">{{ frob(thing) }}</li>
  <li>
</template>

——还有这家店——

const useStore = defineStore("store", {
  state: () => ({ things: ["1", "2", "3"], }),
  actions: { frob(arg) { return `frobbed ${arg}`; } },
});
const store = useStore();

——如果你尝试用storeToRefs解构thingsfrob,你会得到TypeError: $setup.frob is not a function。与 state 和 getter 不同,Action 应该直接从 store 对象中解构:

// wrong
const { things, frob } = storeToRefs(store);

// right
const { things } = storeToRefs(store)
const { frob } = store

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

【讨论】:

    猜你喜欢
    • 2022-12-08
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多