Pinia状态管理
Pinia.js 是新一代的状态管理器,由 Vue.js团队中成员所开发的,因此也被认为是下一代的 Vuex,即 Vuex5.x,完美支持vue3.0。
特点:
- 完全支持typescript
- 轻量级,压缩后体积只有1.6kb
- 只有 store, getters, actions, 移除了mutations
- actions支持同步和异步
- 没有模块嵌套,只有 store 的概念,store 之间可以自由使用,符合 Vue3 的 Composition api,让代码扁平化
- 无需手动添加 store,store 一旦创建便会自动添加
创建store
在src 下创建衣蛾store文件夹,生成一个index.ts文件,导出store
// src/store/index.ts
import { createPinia } from 'pinia'
const store = createPinia()
export default store
全局引入
// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
const app = createApp(App)
app.use(store)
state
定义state
stroe下新建user 文件,注意 每一个状态的id必须唯一且必填
export const useUserInfoStore = defineStore({
id: 'user', // id 必填 唯一
state: () => {
return {
name: '张三',
age: 48,
sex: '男'
}
}
})
获取state
三种方式可以获取state状态
// 1.直接获取store数据
const userInfoStore = useUserInfoStore()
// 2.使用computed 直接访问和修改state数据
const userSex = computed(() => `性别:${userInfoStore.sex}`)
// 3.对state进行解构,但直接结构会失去响应式,使用pinia的storeToRefs属性
const { age } = storeToRefs(userInfoStore)
修改state
- 直接修改其属性值(不建议)
userInfoStore.name = '李四'
- 使用$patch修改多个值
userInfoStore.$patch((state) => {
state.name = '赵六',
state.age = 108
})
- 使用actions修改state,acitons可直接访问this
- 使用$reset重置初始状态
Getters
Pinia 中的 getter 和 Vue 中的计算属性几乎一样,在获取 State值之前做一些逻辑处理
getter 中的值有缓存特性,如果值没有改变,多次使用也只会调用一次
Actions
-
Action 可以直接支持async/await 的语法
export const useUserStore = defineStore({ id: 'user', actions: { async login(account, pwd) { const { data } = await api.login(account, pwd) return data } } }) -
action 间的相互调用,直接用 this 访问即可。
export const useUserStore = defineStore({ id: 'user', actions: { updateAge() { this.age ++ this.consoleName(this.age) }, consoleName(data:any) { console.log(data) } } }) -
在 action 里调用其他 store 里的 action ,引入对应的 store 后即可访问其内部的方法了。
// src/store/user.ts import { useInfoStore } from './info' export const useUserStore = defineStore({ id: 'user', actions: { updateAge() { this.age ++ const InfoStore = useInfoStore() InfoStore.consoleData(this.name, this.age, this.sex) }, } }) // src/store/info.ts export const useInfoStore = defineStore({ id: 'info', actions: { consoleData(name: string, age: number, sex: string) { console.log(`${name}是一个${age}岁的${sex}性`) } } })
pinia-plugin-persist
使用插件 pinia-plugin-persist 可以辅助实现数据持久化功能
使用
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
store.use(piniaPluginPersist)
export default store
接着在对应的 store 里开启 persist 即可
// 开启数据缓存
persist: {
enabled: true
}
数据默认存在 sessionStorage 里,并且会以 store 的 id 作为 key
也可以在 strategies 里自定义 key 值,并将存放位置由 sessionStorage 改为 localStorage
persist: {
enabled: true,
strategies: [
{
key: 'userInfo',
storage: localStorage,
}
]
}
默认所有 state 都会进行缓存,你可以通过 paths 指定要持久化的字段,其他的则不会进行持久化
persist: {
enabled: true,
strategies: [
{
key: 'userInfo',
storage: localStorage,
paths: ['name', 'age']
}
]
}