Pinia 状态
Store 与组合式状态。
Pinia 状态管理
这一课你将能做到
- 用
defineStore创建全局状态仓库 - 使用
state、getters、actions组织状态逻辑 - 在组件中正确读取和修改状态
- 实现模块化状态管理
- 配置状态持久化(localStorage)
为什么要学
组件多了之后,数据共享变成噩梦:A 组件的数据 B 组件要用,C 组件改了 D 组件要同步。props 传不动,事件总线太乱。Pinia 就是「全局数据管家」,集中管理所有共享状态。
人话:Pinia 就像「公司共享文件夹」。每个部门(组件)都可以往里面放文件(state)、读文件(getters)、修改文件(actions),不用部门之间互相传纸条(props/emits)。
先建立图像
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2
},
actions: {
increment() { this.count++ }
}
})
<script setup>
import { useCounterStore } from './stores/counter'
const store = useCounterStore()
</script>
<template>
<p>{{ store.count }} / {{ store.double }}</p>
<button @click="store.increment()">+1</button>
</template>
跟着做
步骤 1:安装与注册
npm install pinia
// main.js
import { createPinia } from 'pinia'
createApp(App).use(createPinia()).mount('#app')
步骤 2:创建 Store
// stores/user.js
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: '',
token: '',
isLogin: false
}),
getters: {
upperName: (state) => state.name.toUpperCase()
},
actions: {
login(name, token) {
this.name = name
this.token = token
this.isLogin = true
},
logout() {
this.$reset()
}
}
})
步骤 3:组件中使用
<script setup>
import { useUserStore } from '../stores/user'
const user = useUserStore()
function handleLogin() {
user.login('张三', 'token123')
}
</script>
<template>
<div v-if="user.isLogin">
<p>欢迎,{{ user.name }}({{ user.upperName }})</p>
<button @click="user.logout()">退出</button>
</div>
<button v-else @click="handleLogin">登录</button>
</template>
步骤 4:组合式风格(推荐)
// stores/counter.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const double = computed(() => count.value * 2)
function increment() { count.value++ }
return { count, double, increment }
})