Vue 3 与 Pinia 状态管理教程
Pinia简介
Pinia是Vue 3生态系统中的现代状态管理库,相比Vuex有以下优势:
- 更轻量级
- 完整的TypeScript支持
- 模块化设计
- 直观的API
- 更好的代码组织
安装与配置
安装Pinia
使用npm安装:
            
            
              bash
              
              
            
          
          npm install pinia使用yarn安装:
            
            
              bash
              
              
            
          
          yarn add pinia项目配置
在main.ts或main.js中引入并使用:
            
            
              typescript
              
              
            
          
          import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')核心概念
State(状态)
State是store的核心,定义了应用的数据状态。
Getters(计算属性)
类似于计算属性,可以derived当前状态的新状态。
Actions(动作)
处理业务逻辑和状态变更的方法。
创建与使用Store
基本Store示例
            
            
              typescript
              
              
            
          
          // stores/counter.ts
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
  // 状态
  state: () => ({
    count: 0,
    name: 'John Doe'
  }),
  // 计算属性
  getters: {
    doubleCount(): number {
      return this.count * 2
    },
    
    fullName(): string {
      return `User: ${this.name}`
    }
  },
  // 动作
  actions: {
    increment() {
      this.count++
    },
    decrement() {
      this.count--
    },
    resetCounter() {
      this.count = 0
    }
  }
})在组件中使用Store
            
            
              vue
              
              
            
          
          <template>
  <div>
    <p>Count: {{ counter.count }}</p>
    <p>Double Count: {{ counter.doubleCount }}</p>
    <button @click="counter.increment">+</button>
    <button @click="counter.decrement">-</button>
  </div>
</template>
<script setup>
import { useCounterStore } from '@/stores/counter'
// 获取store实例
const counter = useCounterStore()
</script>高级特性
持久化存储
使用pinia-plugin-persistedstate实现状态持久化:
            
            
              bash
              
              
            
          
          npm install pinia-plugin-persistedstate
            
            
              typescript
              
              
            
          
          import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)组合式API风格Store
            
            
              typescript
              
              
            
          
          import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', () => {
  // 状态
  const username = ref('')
  const isLoggedIn = ref(false)
  // 计算属性
  const greeting = computed(() => `Hello, ${username.value}`)
  // 动作
  function login(name: string) {
    username.value = name
    isLoggedIn.value = true
  }
  function logout() {
    username.value = ''
    isLoggedIn.value = false
  }
  return { 
    username, 
    isLoggedIn, 
    greeting, 
    login, 
    logout 
  }
})最佳实践
- 将Store拆分为多个独立的模块
- 使用TypeScript增强类型安全
- 避免在Store中存储过多状态
- 合理使用getters进行状态派生
- 使用$reset()方法重置状态
- 利用$patch()进行批量状态更新
注意事项
- Pinia中的store是响应式的
- 可以直接解构store,但建议使用storeToRefs()保持响应性
- 尽量在actions中处理复杂的状态变更逻辑
结语
Pinia提供了简洁、强大的状态管理方案,极大地简化了Vue 3应用的状态管理复杂度。掌握Pinia,将帮助您构建更加健壮和可维护的前端应用。