选项式调用
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博客