Pinia 是 Vue.js 的官方状态管理库,它提供了直观且类型安全的方式来管理应用状态。下面为你提供一个快速入门指南:
1. 安装 Pinia
首先,确保你已经安装了 Vue 3 项目,然后通过 npm 或 yarn 安装 Pinia:
npm install pinia
# 或
yarn add pinia
2. 创建并配置 Pinia 实例
在你的 Vue 项目中,创建一个 Pinia 实例并在应用中注册:
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')
3. 创建第一个 Store
Store 是 Pinia 中的核心概念,类似于 Vuex 中的 store。下面创建一个简单的 counter store:
import { defineStore } from 'pinia'
// 使用组合式 API 风格创建 store
export const useCounterStore = defineStore('counter', () => {
// 状态
const count = ref(0)
// 获取器 (getters)
const doubleCount = computed(() => count.value * 2)
// 动作 (actions)
function increment() {
count.value++
}
function incrementBy(value) {
count.value += value
}
// 返回所有状态和方法
return { count, doubleCount, increment, incrementBy }
})
// 也可以使用选项式 API 风格 (与 Vue 2 兼容)
// export const useCounterStore = defineStore('counter', {
// state: () => ({
// count: 0
// }),
// getters: {
// doubleCount: (state) => state.count * 2
// },
// actions: {
// increment() {
// this.count++
// }
// }
// })
4. 在组件中使用 Store
创建好 store 后,可以在任何组件中使用它:
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Double Count: {{ counter.doubleCount }}</p>
<button @click="counter.increment">+</button>
<button @click="counter.incrementBy(5)">+5</button>
</div>
</template>
<script setup>
import { useCounterStore } from '../stores/counter'
// 获取 store 实例
const counter = useCounterStore()
// 也可以解构 store 中的属性
// const { count, increment } = useCounterStore()
// 注意:直接解构会失去响应性,需要使用 storeToRefs
// import { storeToRefs } from 'pinia'
// const { count } = storeToRefs(useCounterStore())
</script>
5. Store 特性详解
状态管理
Pinia 的状态是响应式的,可以直接修改:
// 在 store 中
const count = ref(0)
count.value++
// 或在 actions 中
function increment() {
count.value++
}
Getters (获取器)
类似于计算属性,用于派生状态:
const doubleCount = computed(() => count.value * 2)
Actions (动作)
用于处理逻辑和修改状态:
function increment() {
count.value++
}
// 异步操作
async function fetchData() {
const response = await fetch('https://api.example.com/data')
const data = await response.json()
// 更新状态
}
6. 插件和持久化
Pinia 支持插件扩展,可以添加如持久化等功能:
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
export default pinia
然后在 store 中启用持久化:
export const useCounterStore = defineStore('counter', () => {
// 状态定义...
}, {
persist: true // 启用持久化
// 或自定义配置
// persist: {
// key: 'my-custom-key',
// storage: localStorage,
// paths: ['count'] // 只持久化 count 字段
// }
})
7. 类型安全
Pinia 对 TypeScript 提供了一流的支持:
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useUserStore = defineStore('user', () => {
// 明确类型定义
const user = ref<User | null>(null)
function setUser(newUser: User) {
user.value = newUser
}
return { user, setUser }
})
interface User {
id: number
name: string
email: string
}
总结
Pinia 是 Vue 3 的官方状态管理库,相比 Vuex 更加简洁和灵活:
- 使用
defineStore创建 store - 支持组合式 API 和选项式 API
- 内置类型安全
- 没有 mutations,只有 state、getters 和 actions
- 支持插件扩展
- 更好的 Tree-shaking 支持
这只是一个快速入门,Pinia 还有更多高级功能,如订阅、测试等,可以参考 Pinia 官方文档 深入学习。
387

被折叠的 条评论
为什么被折叠?



