vue3引入pinia
时间: 2025-02-07 15:08:46 浏览: 43
### 安装和配置 Pinia 在 Vue 3 项目
为了在 Vue 3 项目中安装并配置 Pinia 状态管理库,可以遵循以下方法:
#### 使用 npm 或 yarn 安装 Pinia 库
通过包管理工具来获取最新版本的 Pinia。
```bash
npm install pinia @pinia/web-extension
```
或者如果偏好使用 `yarn`:
```bash
yarn add pinia @pinia/web-extension
```
#### 创建 Pinia 实例并与应用关联
创建一个新的 JavaScript 文件用于初始化 Pinia 插件实例,并将其挂载到 Vue 应用上。通常这个操作会在项目的入口文件完成,比如 main.js 中。
```javascript
// src/main.js or equivalent entry file
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
```
#### 定义 Store (仓库)
定义一个 store 来保存应用程序的状态逻辑。这可以通过创建单独的模块化 stores 来实现,每个 store 都有自己的 state、getters 和 actions 方法集。
```javascript
// src/stores/counterStore.js as an example of a simple counter store.
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('main', {
state: () => ({
count: 0,
}),
getters: {
doubleCount(): number {
return this.count * 2;
},
},
actions: {
increment() {
this.count++;
}
}
});
```
之后可以在组件内部轻松访问此存储的数据以及调用其 action 函数更新数据。
```javascript
<script setup>
import { useCounterStore } from '../stores/counterStore';
const counter = useCounterStore();
</script>
<template>
<p>Current Count is {{ counter.count }}</p>
<button @click="counter.increment">Increment Counter</button>
</template>
```
阅读全文
相关推荐




















