pinia使用组合式
时间: 2023-11-18 08:52:33 浏览: 130
Pinia 是一个 Vue.js 状态管理库,它使用组合式 API 来管理状态。组合式 API 是 Vue.js 3.0 中引入的一种新的 API,它提供了一种更加灵活和直观的方式来组织和管理组件的状态。
使用 Pinia,我们可以通过定义一个 store 来管理应用程序的状态。一个 store 可以包含多个 state、getter、mutation 和 action,这些都是通过组合式 API 来定义的。我们可以在组件中使用 useStore() 函数来访问 store 中的状态和方法。
下面是一个使用 Pinia 的示例:
```javascript
import { defineStore } from 'pinia'
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 0
}),
getters: {
doubleCount: state => state.count * 2
},
actions: {
increment() {
this.count++
}
}
})
```
在组件中使用:
```javascript
import { useCounterStore } from './store'
export default {
setup() {
const counterStore = useCounterStore()
function handleClick() {
counterStore.increment()
}
return {
count: counterStore.count,
doubleCount: counterStore.doubleCount,
handleClick
}
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)