Pinia 基础知识
前言
说明
- 本篇更倾向于
选项式 API
写法,因为项目是从Vue2
升级至Vue3
,为更好且快速适配; Vue2
中,Vuex3
与Pinia
不能一起使用。因为Pinia
使用的是Vuex3
现有接口;Vue3
中,Vuex4
与Pinia
可以一起使用;
与 Vuex 的差异
- 参考 从 Vuex ≤4 迁移;
Pinia
废弃mutation
;
Store/Pinia 是什么
- 承载着全局状态;
- 一个保存状态和业务逻辑的实体,它并不与你的组件树绑定;
- 可理解为一个永远存在的组件,每个组件都可以读取和写入它;
- 三个概念:
state, getter, action
,可理解为组件中的data, computed, methods
; - store 是一个用
reactive
包装的对象,不用在 getter 后面写.value
; - store 不能解构,否则失去响应性。使用
storeToRefs()
解构可保持响应性;
<script setup>
import { storeToRefs } from 'pinia'
const store useCounterStore()
const { name, doubleCount } = storeToRefs(store)
</script>
核心概念
定义 Store
- 使用
defineStore
定义,变量名建议以use
开头且以Store
结尾,例如:useUserStore
; - 第一个参数要求 独一无二 ,且必传。它用来连接 store 和 devtools;
- 第二个参数可接受两种类值:Setup 函数或 Option 对象。具体参考此处;
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
// ...
})
State
state
是store
的核心;state
被定义为一个返回初始化状态的函数。使得其可同步支持服务端和客户端(不理解…);- 为了完整类型推理,推荐使用箭头函数;
// 选项式API方式
import { defineStore } from 'pinia'
const userUserStore = defineStore('user', {
// 使用箭头函数
state: ()=> {
return {
name: 'admin',
age: 30,
}
}
})
使用
通过实例访问,直接读写;
const store = userUserStore();
store.name
重置 state
选项式 API
直接调 $reset()
方法。组合式API
要自己创建,参考此处。
const store = userUserStore();
store.$reset()
只读的计算属性
使用 mapState()
辅助函数将 state
映射为只读的计算属性。
import { mapState } from 'pinia'
import { useUserStore } from '../stores/user'
export default {
computed: {
// 直接用 this.name,与 store.name 数据相同
...mapState(useUserStore, ['name']),
...mapState(useUserStore, {
// 与上述相同,但注册为 this.myName
myName: 'name',
// 也可以用函数
fullName: store => store.name + 'Liu',
// 可以访问 this,但没标注类型
UserString(store) {
return store.age + this.fullName
}
})
}
}
可修改的计算属性
使用 mapWritableState()
辅助函数,但不能像 mapState()
传递成一个函数
import { mapWritableState } from 'pinia'
import { useUserStore } from '../stores/user'
export default {
computed: {
// 直接用 this.name,与 store.name 数据相同。且能改变 this.name = '123'
...mapWritableState(useUserStore, ['name']),
...mapWritableState(useUserStore, {
// 与上述相同,但注册为 this.myName。但没有函数方式
myName: 'name',
})
}
}
变更 state
- 使用
$patch
,两种方式:对象方式和函数方式; - 区别是 p a t c h ( ) 允许你将多个变更归入 d e v t o o l s 的同一个条目中。同时请注意,直接修改 s t a t e , patch() 允许你将多个变更归入 devtools 的同一个条目中。同时请注意,直接修改 state, patch()允许你将多个变更归入devtools的同一个条目中。同时请注意,直接修改state,patch() 也会出现在 devtools 中,而且可以进行 time travel (在 Vue 3 中还没有)。不理解…
// 方式一:对象方式
store.$patch({
count: store.count + 1,
age: 120,
name: 'DIO',
})
// 方式二:函数方式
store.$patch((state) => {
state.items.push({ name: 'shoes', quantity: 1 })
state.hasChanged = true
})
替换 state
// 这实际上并没有替换`$state`
store.$state = { count: 24 }
// 在它内部调用 `$patch()`:
store.$patch({ count: 24 })
Getter
- 完全等同于 store 的 state 计算值,使用
getters
属性来定义; - 推荐使用箭头函数,并将接收 state 作为第一个参数;
- 通过 this 访问 store 实例或其它 getter 值;
// 定义
export const useCounterStore = defineStore('counter', {
state:() {
return {
count: 0,
}
},
getters: {
// 通过第一个参数 state 访问 count
doubleCount(state) {
return state.count * 2
},
// 通过 this 访问其它 getter 值
doublePlusOne() {
return this.doubleCount + 1
}
}
})
// 访问
<script setup>
import { useCounterStore } from './counterStore'
const store = useCounterStore()
</script>
<template>
<p>Double count is {{ store.doubleCount }}</p>
</template>
- 向 getter 传递参数,getter 是幕后的计算属性,所以不可以向它们传递任务参数。但可以返回一个函数,函数可接受任意参数;
export const useUserListStore = defineStore('userList', {
getters: {
getUserById(state) {
return (useId) => state.userd.find((user) => user.id === userId)
}
}
})
- 想要使用另一个 store 的 getter,直接在 getter 内使用即可;
import { useOtherStore } from './other-store'
export const useStore = defineStore('main', {
state:() => {
//...
},
getters: {
otherGetter(state) {
const otherStore = useOtherStore()
return state.localData + otherStore.data
}
}
})
- setup 中使用,直接访问就行,与 state 属性完全一样;
<script setup>
const store = useCounterStore()
store.count = 3
store.doubleCount // 6
</script>
- 使用
mapState()
函数将其映射为 getters,与 state 用法一致;
Action
- 相对于组件中的 method,可通过 defineStore() 中的 actions 属性定义;
- 它们也是定义业务逻辑的完美选择;
- 类似 getter,action 也可通过 this 访问整个 store 实例;
- 不同之处,action 可以是异步的,可使用 async 或 Promise;
import { mande } from 'mande'
const api = mande('/api/users')
export const useUsers = defineStore('users', {
state: () => {
return {
userData: null,
}
},
actions: {
async registerUser(login, password) {
try {
this.userData = await api.post({login, password})
} catch(error) {
showTooltip(error)
}
}
}
})
调用:可以像函数或通常意义上的方法一样被调用;
<script setup>
const store = useCounterStore();
// 将 action 作为 store 的方法进行调用
store.randomizeCounter()
</script>
<template>
<!-- 即使在模板中也可以 -->
<button @click="store.randomizeCounter()"></button>
</template>
访问其它 store 的 action,直接在 action 中调就好了;
选项式API的用法
import { defineStore } from 'pinia'
const userCounterStore = defineStore('counter', {
state: () => {
count: 0
},
actions: {
increment() {
this.count++;
}
}
})
- 使用 setup();
- 不使用 setup():
mapActions
辅助函数将action属性映射为你组件中的方法;
组件外的 Store
单页面应用
- app.use(pinia) 安装后,对 useStore() 的调用才能正常使用;
- 为确保 pinia 实例北极狐,最简单的方法是将 useStore() 调用放在 pinia 安装之后再执行的函数中;
import { useUserStore } from '@/stores/user'
import { createApp } from 'vue'
import App from './App.vue'
// 错误
const userStore = useUserStore()
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
// 正确,因为 pinia 实例现在被激活
const userStore = useUserStore()