pinia的使用

一、安装Pinia

可以通过npm或yarn进行安装

npm install pinia

或者:

yarn add pinia

二、在main.js中引入并注册Pinia:

  • 在项目的入口文件(如main.jsmain.ts)中,导入createPinia方法,并创建一个Pinia实例,然后将其注册到Vue应用中。
  •   import { createApp } from 'vue';
         import { createPinia } from 'pinia';
         import App from './App.vue';
    
         const pinia = createPinia();
         const app = createApp(App);
         app.use(pinia);
         app.mount('#app');

    三、创建Store:

  • 在项目的src/store目录下新建一个文件(如index.jsindex.ts),使用defineStore函数定义Store。
  •      import { defineStore } from 'pinia';
    
         export const useStore = defineStore('store', {
           state: () => ({
             counter: 0,
           }),
           actions: {
             increment() {
               this.counter++;
             },
           },
         });
    

    这一步定义了Store的基本结构,包括状态(state)、计算属性(getters)和动作(actions)四、在组件中使用Store:

  • 在需要使用Store的组件中,通过useStore函数导入Store实例,并在模板和脚本中使用Store中的数据和方法。
  • 例:
         <template>
           <div>{{ store.counter }}</div>
           <button @click="store.increment">Increment</button>
         </template>
    
         <script setup>
         import { useStore } from '../store';
    
         const store = useStore();
         </script>
    

<think> 我们正在回答用户关于Pinia使用方法的提问。根据引用内容,我们可以总结出Pinia的基本使用步骤,包括安装、注册、创建store以及在组件中使用。此外,引用[3]还提到了状态持久化的方法。 注意:用户之前的问题是关于页面间方法调用,但当前问题聚焦于Pinia使用教程。因此,我们将专注于讲解Pinia使用。 回答结构: 1. 介绍Pinia(是什么,为什么用) 2. 安装Pinia 3. 创建Pinia实例并注册到Vue应用 4. 创建Store(选项式和组合式两种写法) 5. 在组件中使用Store 6. 状态持久化(使用插件) 我们将参考引用[1][2][3]的内容,但注意引用[2]中的代码格式可能有误,我们将给出正确示例。 </think> 下面是 Pinia 状态管理库的完整使用教程,包含基础安装、核心功能和进阶技巧: ### 一、Pinia 核心优势 1. **Vue3 官方推荐**:替代 Vuex 的轻量级状态管理方案 2. **TypeScript 支持**:完整的类型推断 3. **模块化设计**:每个 Store 都是独立模块 4. **Devtools 集成**:支持 Vue Devtools 调试 5. **极简 API**:学习曲线平缓,减少样板代码 --- ### 二、基础安装与配置 #### 1. 安装依赖 ```bash npm install pinia # 或 yarn add pinia ``` #### 2. 初始化配置(main.js) ```javascript import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' const pinia = createPinia() const app = createApp(App) app.use(pinia) app.mount('#app') ``` --- ### 三、创建 Store 的两种方式 #### 选项式写法(Options API) ```javascript // stores/counter.js import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++ }, async fetchData() { const res = await fetch('/api/data') this.data = await res.json() } }, getters: { doubleCount: (state) => state.count * 2 } }) ``` #### 组合式写法(Composition API) ```javascript // stores/user.js import { defineStore } from 'pinia' import { ref, computed } from 'vue' export const useUserStore = defineStore('user', () => { const user = ref(null) const isLoggedIn = computed(() => !!user.value) function login(email, password) { // 登录逻辑 } return { user, isLoggedIn, login } }) ``` --- ### 四、在组件中使用 Store #### 1. 基本使用 ```vue <script setup> import { useCounterStore } from '@/stores/counter' const counter = useCounterStore() </script> <template> <div>当前计数: {{ counter.count }}</div> <button @click="counter.increment()">+1</button> <div>双倍值: {{ counter.doubleCount }}</div> </template> ``` #### 2. 跨组件通信(兄弟组件) ```vue <!-- ComponentA.vue --> <script setup> import { useCounterStore } from '@/stores/counter' const store = useCounterStore() </script> <template> <button @click="store.increment">更新计数器</button> </template> <!-- ComponentB.vue --> <script setup> import { useCounterStore } from '@/stores/counter' const store = useCounterStore() </script> <template> <div>接收更新: {{ store.count }}</div> </template> ``` --- ### 五、状态持久化(刷新保留数据) #### 1. 安装插件 ```bash npm install pinia-plugin-persistedstate ``` #### 2. 配置持久化(src/main.js) ```javascript import { createPinia } from 'pinia' import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(piniaPluginPersistedstate) ``` #### 3. Store 启用持久化 ```javascript export const useAuthStore = defineStore('auth', { state: () => ({ token: null }), persist: true // 开启持久化 }) // 自定义配置 persist: { key: 'user-auth', // 存储键名 storage: sessionStorage, // 可选 localStorage/sessionStorage paths: ['token'] // 只持久化指定字段 } ``` --- ### 六、最佳实践技巧 1. **模块化拆分**:按功能域创建独立 Store ```bash src/stores/ ├── cart.js ├── user.js └── settings.js ``` 2. **响应式解构**:保持状态响应性 ```javascript import { storeToRefs } from 'pinia' const store = useCounterStore() const { count, doubleCount } = storeToRefs(store) // 保持响应性 ``` 3. **重置状态**:快速恢复初始值 ```javascript const store = useCounterStore() store.$reset() // 重置整个store ``` 4. **订阅状态变化**: ```javascript store.$subscribe((mutation, state) => { console.log('状态变化:', mutation.type) }) ``` --- ### 七、Pinia vs 事件总线 | **特性** | Pinia | 事件总线 (mitt) | |------------------|------------------------|----------------------| | 状态管理 | ✅ 集中式状态存储 | ❌ 仅事件通信 | | 响应式 | ✅ 自动跟踪依赖 | ❌ 需手动处理 | | 时间旅行调试 | ✅ 支持 | ❌ 不支持 | | TypeScript 支持 | ✅ 完整类型推断 | ⚠️ 基础类型支持 | | 持久化 | ✅ 内置插件支持 | ❌ 需手动实现 | | 适用场景 | 跨组件/页面状态共享 | 简单事件通知 | > Pinia 提供了更完整的状态管理解决方案,特别适合中大型应用[^1],而事件总线更适合简单的事件通知场景[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值