安装:
yarn add pinia
# 或者使用 npm
npm install pinia
在项目的 main.js 文件中引入:
import { createPinia,Pinia } from "pinia";
const pinia = createPinia();
app.use(pinia);
然后你在项目中定义一个 文件夹: counter==>test.ts
import { defineStore } from "pinia";
export const useCounterStore = defineStore('counter', { // counter为这个存储库的名字
state: () => {
return { count: 0 }
},
// 也可以定义为
// state: () => ({ count: 0 })
actions: {
increment() {
this.count++
},
},
})
在组件中使用:
import { useCounterStore } from '@/stores/counter'
export default {
setup() {
const counter = useCounterStore(); //这里的counter就是我们在test.ts中的存储库的counter名字
console.log(counter.count) // 打印: 0
counter.count++
// 带自动补全 ✨
counter.$patch({ count: counter.count + 1 })
// 或使用 action 代替
counter.increment()
},
}