重要:使用 Pinia 映射函数的前提是使用
选项式API
,而不是组合式API
参考链接:https://pinia.vuejs.org/zh/cookbook/options-api.html
前言
- 若你选择使用
选项式API
或者正在迁移一个选项式API的应用,可以试试 Pinia 提供的类似 Vuex
的映射辅助函数
- 还是像 上一篇 的方式来定义 Store,然后通过
mapStores()
、mapState()
、mapWritableState()
或mapActions()
访问 - 不再使用 mapGetters、mapMutations
一、mapStores
- 如果需要访问 store 里的大部分内容,映射 store 的每一个属性太麻烦。可以用
mapStores()
来访问整个 store
- 默认情况下,Pinia 会在每个 store 的 id 后面加上
"Store"
的后缀,所以映射后使用时,通过idStore.xx
import { mapStores } from 'pinia'
// 给出具有以下 id 的两个 store
const useUserStore = defineStore('user', {
// ...
})
const useCartStore = defineStore('cart', {
// ...
})
export default {
computed: {
// 注意,我们不是在传递一个数组,而是一个接一个的 store。
// 可以 id+'Store' 的形式访问每个 store 。
...mapStores(useCartStore, useUserStore)
},
methods: {
async buyStuff() {
// 可以在任何地方使用他们!
if (this.userStore.isAuthenticated()) {
await this.cartStore.buy()
this.$router.push('/purchased')
}
},
},
}
二、mapState
- 可以使用
mapState()
辅助函数将 state 属性映射为只读的计算属性
(不再使用 mapGetters) - 使用
数组
直接同名映射
:…mapState(store, [‘count’]) - 使用
对象
可映射为新的名称
:…mapState(store, { key: value, fn (state) })- 使用对象时,
value
值可以是字符串
,可以是函数
; - 对象内部也可以直接定义
函数
,接收store
作为参数
- 使用对象时,
- 见以下 4 种使用方式
import { mapState } from 'pinia'
import { useCounterStore } from '../stores/counter'
export default {
computed: {
// 可以访问组件中的 this.count
// 与从 store.count 中读取的数据相同
...mapState(useCounterStore, ['count'])
// 与上述相同,但将其注册为 this.myOwnName
...mapState(useCounterStore, {
myOwnName: 'count',
// 你也可以写一个函数来获得对 store 的访问权
double: store => store.count * 2,
// 它可以访问 `this`,但它没有标注类型...
magicValue(store) {
return store.someGetter + this.count + this.double
},
}),
},
}
三、mapWritableState
- 如果你想修改这些 state 属性,使用
mapWritableState()
作为代替 - 区别是
不能
像 mapState() 那样传递函数
import { mapWritableState } from 'pinia'
import { useCounterStore } from '../stores/counter'
export default {
computed: {
// 可以访问组件中的 this.count,并允许设置它。
// this.count++
// 与从 store.count 中读取的数据相同
...mapWritableState(useCounterStore, ['count'])
// 与上述相同,但将其注册为 this.myOwnName
...mapWritableState(useCounterStore, {
myOwnName: 'count',
}),
},
}
四、mapActions
- 可以使用
mapActions()
辅助函数将action
属性映射为你组件中的方法
- 同样
不允许
传入函数
import { mapActions } from 'pinia'
import { useCounterStore } from '../stores/counter'
export default {
methods: {
// 访问组件内的 this.increment()
// 与从 store.increment() 调用相同
...mapActions(useCounterStore, ['increment'])
// 与上述相同,但将其注册为this.myOwnName()
...mapActions(useCounterStore, { myOwnName: 'increment' }),
},
}