举个pinia的使用例子
时间: 2024-07-31 22:01:56 浏览: 163
Pinia是Vue 3.x官方推荐的状态管理库,它基于Vuex的设计理念,但更轻量、更易用。下面是一个简单的Pinia使用例子:
首先,你需要安装`@vue/pinia`:
```bash
npm install @vue/pinia
```
创建一个store文件,比如`store.js`:
```javascript
import { createStore } from '@vue/pinia'
export const store = createStore({
id: 'myStore',
state() {
return {
count: 0,
}
},
actions: {
increment(context) {
context.commit('incrementCount')
},
},
mutations: {
incrementCount(state) {
state.count++
},
},
})
```
在组件中,你可以通过注入来访问store:
```html
<template>
<button @click="increment">Increment</button>
<p>Count: {{ count }}</p>
</template>
<script setup>
import { useStore } from '@vue/pinia'
const { state, dispatch } = useStore('myStore')
function increment() {
dispatch('increment')
}
</script>
```
在这个例子中,当点击按钮时,`increment`函数会触发`incrementCount`动作,然后更新store中的`count`状态。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)