vue3 pinia获取store
时间: 2025-01-13 15:51:14 浏览: 63
### 如何在 Vue 3 中使用 Pinia 获取 Store
为了在 Vue 3 应用程序中利用 Pinia 进行状态管理,开发者可以遵循特定的方法来创建并访问 store 实例。Pinia 提供了一个更为简洁的 API 设计以及良好的 TypeScript 支持特性[^1]。
#### 创建 Store
首先需要安装 `pinia` 包,并初始化一个新的 pinia 实例:
```bash
npm install pinia
```
接着定义一个或多个 stores 文件夹内的模块文件,例如命名为 `useCounterStore.js`:
```javascript
// src/stores/useCounterStore.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++
},
},
})
```
此代码片段展示了如何通过调用 `defineStore` 函数来声明名为 `'counter'` 的 store 模块,其中包含了初始的状态属性 `count` 和用于修改该状态的动作方法 `increment()`。
#### 初始化 Pinia 并挂载到应用实例上
为了让整个应用程序能够识别和使用这些自定义的 store,还需要完成如下配置工作:
```javascript
// main.js 或 setup 入口处
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
```
这段脚本说明了怎样引入必要的依赖项并将新建立好的 pinia 插件注册给 vue 应用对象以便后续操作。
#### 访问 Store 数据
一旦完成了上述准备工作之后,在组件内部就可以很方便地获取所需的 store 资源了。下面是一个具体的例子展示如何在一个单文件组件里读取 counter 值并且触发其更新行为:
```html
<template>
<div class="greetings">
<h1>Count is {{ counter }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import { useCounterStore } from '../stores/useCounterStore'
const store = useCounterStore()
let counter = computed(() => store.count)
function increment() {
store.increment()
}
</script>
```
在此模板中,`computed` 属性被用来监听来自 store 的实时变化;同时按钮点击事件绑定到了由 store 定义的操作函数之上,从而实现了界面交互逻辑与底层数据层之间的解耦合设计模式。
阅读全文
相关推荐


















