import { reactive, computed } from 'vue'
// 简单的状态存储类
class Store {
constructor(options) {
// 响应式状态
this.state = reactive(options.state())
// 处理 getters
this.getters = {}
if (options.getters) {
for (const key in options.getters) {
this.getters[key] = computed(() => options.getters[key](this.state))
}
}
// 处理 actions
if (options.actions) {
for (const key in options.actions) {
this[key] = options.actions[key].bind(this)
}
}
}
}
// 定义 store 的创建方法
function defineStore(id, options) {
let store
return function useStore() {
if (!store) {
store = new Store(options)
}
return store
}
}
// 导出 defineStore
export { defineStore }
使用自定义的pinia
import { defineStore } from './simplePinia' // 引入刚刚定义的简单 Pinia
// 定义一个 store
const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
getters: {
doubleCount(state) {
return state.count * 2
}
},
actions: {
increment() {
this.state.count++
},
incrementBy(value) {
this.state.count += value
}
}
})
// 在组件中使用 store
export default {
setup() {
const counterStore = useCounterStore()
return {
count: counterStore.state.count,
doubleCount: counterStore.getters.doubleCount,
increment: counterStore.increment,
incrementBy: counterStore.incrementBy
}
}
}