在非 setup 中使用 Pinia
即使您不使用组合 API,也可以使用 Pinia(如果您使用的是 Vue <2.7,您仍然需要安装@vue/composition-api插件)。虽然我们建议您尝试使用 Composition API 并学习它,但您和您的团队可能还不是时候,您可能正在迁移应用程序或任何其他原因。有几个功能:
- mapStores
- mapState
- mapWritableState
- mapGetters(只是为了迁移方便,请用
mapState()代替) - mapActions
mapStores()
如果你需要访问 store 里的大部分内容,映射 store 的每一个属性可能太麻烦。您可以通过mapStores()来访问整个 store:
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')
}
},
},
}
默认情况下,Pinia 会在每个 store 的id后面加上Store的后缀。你可以通过调用setMapStoreSuffix()来自定义:
import { createPinia, setMapStoreSuffix } from 'pinia'
// 完全删除后缀:this.user, this.cart
setMapStoreSuffix('')
// this.user_store, this.cart_store (没关系,我不会批评你的)
setMapStoreSuffix('_store')
export const pinia = createPinia()
TypeScript
默认情况下,所有映射辅助函数都支持自动补全,你不需要做任何事情。如果你调用setMapStoreSuffix()修改了Store的后缀,你还需要在 TS 文件或global.d.ts文件的某个地方添加它。最方便的地方就是你调用setMapStoreSuffix()的地方:
import { createPinia, setMapStoreSuffix } from 'pinia'
setMapStoreSuffix('') // 完全删除后缀
export const pinia = createPinia()
declare module 'pinia' {
export interface MapStoresCustomization {
// 设置成和上面一样的值
suffix: ''
}
}
