pinia选项式与函数式调用下$reset的不同表现形式

选项式调用

import { defineStore } from "pinia";

// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useIndexStore = defineStore("index", {
  state: () => ({
    count: 999,
  }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++;
    },
  },
});
<template>
  <div>{{ storeIndex.count }}</div>
  <div>{{ storeIndex.double }}</div>
  <button @click="storeIndex.$reset">reset</button>
  <input type="text" v-focus>
</template>
<script setup>
import { useIndexStore } from '@/stores/index'

const storeIndex = useIndexStore();
</script>

此状态下的reset方法可以正常执行

函数式调用

import { defineStore } from "pinia";
import { computed, ref } from "vue";

// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useCountStore = defineStore("count", () => {
  const count = ref(10);
  
  const double = computed(() => count.value * 2)
  
  function increment () {
    count.value++
  }

  return {
    count,
    increment,
    double
  }
});
<template>
  <div>{{ storeCount.double }}</div>
  <button @click="storeCount.increment">add count</button>
  <button @click="storeCount.$reset">reset</button>
  <input type="text" v-focus>
</template>
<script setup>
import { useCountStore } from '@/stores/count'

const storeCount = useCountStore();
</script>

此状态下的reset方法调用会异常

runtime-core.esm-bundler.js:221 Uncaught Error: 🍍: Store "count" is built using the setup syntax and does not implement $reset().
    at Proxy.$reset (pinia.mjs:1329:27)
    at _createElementVNode.onClick._cache.<computed>._cache.<computed> 
    at callWithErrorHandling (runtime-core.esm-bundler.js:158:18)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:166:17)
    at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js:278:5)

经调查发现,在函数式调用时,需要全局声明后使用,详见用setup方式编写pinia无法调用reset时_"store \"counter\" is built using the setup syntax_toobeloong的博客-CSDN博客

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值