如何在 vue 应用程序中使用 pinia 状态管理库?安装 pinia创建 store 模块使用 store
如何使用 Pinia
Pinia 是 Vue 3 的状态管理库,它提供了开箱即用的开发生态系统,以便在 Vue 应用程序中管理状态。
安装
npm install pinia
创建 Store
立即学习“前端免费学习笔记(深入)”;
创建一个 store 模块:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
},
decrement() {
this.count--
}
}
})
使用 Store
在 Vue 组件中使用 store:
<script setup>
import { useCounterStore } from '../stores/counter'
const counterStore = useCounterStore()
</script><template><div>
<p>Count: {{ counterStore.count }}</p>
<button>+</button>
<button>-</button>
</div>
</template>
特性
Pinia 提供了以下特性: