import { defineStore } from 'pinia'
pinia
是一个状态管理库,用于 Vue.js 应用程序,与 Vuex 类似但更轻便,并且有许多优化和改进。
defineStore
是 pinia
中的一个函数,用于定义一个 store。store 是存储应用级别状态和逻辑的地方。
以下是使用 defineStore
的一个基本示例:
import { defineStore } from 'pinia'
export const useStore = defineStore({
// 必须唯一
id: 'main',
// 定义 store 的状态(state)
state: () => ({
counter: 0
}),
// 定义该 store 的行为(actions)
actions: {
increment() {
this.counter++
}
}
})
然后你可以在组件中按需使用此 store:
import { useStore } from '@/stores/main'
export default {
setup() {
const store = useStore()
return {
counter: store.counter,
increment: store.increment
}
}
}
在上述代码中,useStore
是一个自定义函数,当在组件中调用它时,会返回我们定义的 store,你可以访问其状态(state)和行为(actions)。