pinia stores
时间: 2023-12-05 22:41:15 浏览: 40
Pinia是一个Vue状态管理库,它提供了一种简单的方法来管理Vue应用程序中的状态。Pinia stores是指在Pinia中定义的状态管理器,它们由状态、getter和action组成。下面是一个使用Pinia stores的例子:
```javascript
// 引入Pinia和defineStore
import { createPinia, defineStore } from 'pinia'
// 创建Pinia实例
const pinia = createPinia()
// 定义一个store
export const useCounterStore = defineStore({
// store的唯一标识符
id: 'counter',
// store的状态
state: () => ({
count: 0
}),
// store的getter
getters: {
doubleCount() {
return this.count * 2
}
},
// store的action
actions: {
increment() {
this.count++
}
}
})
// 在组件中使用store
import { useCounterStore } from './store'
export default {
setup() {
// 获取store实例
const counterStore = useCounterStore()
// 使用store的状态
const count = counterStore.count
// 使用store的getter
const doubleCount = counterStore.doubleCount
// 使用store的action
const increment = counterStore.increment
return {
count,
doubleCount,
increment
}
}
}
```