Usage without setup()
#
即使您不使用组合 API,也可以使用 Pinia(如果您使用的是 Vue <2.7,您仍然需要安装 @vue/composition-api
插件)。 虽然我们建议您尝试使用 Composition API 并学习它,但您和您的团队可能还不是时候,您可能正在迁移应用程序或任何其他原因。 有几个功能:
- mapStores
- mapState
- mapWritableState
- ⚠️ mapGetters (just for migration convenience, use
mapState()
instead) - mapActions
授予对整个商店的访问权限 #
如果您需要访问商店中的几乎所有内容,则映射商店的每个属性可能太多了......相反,您可以使用 mapStores()
访问整个商店:
js
import { mapStores } from 'pinia'
// 给定两个具有以下 id 的商店
const useUserStore = defineStore('user', {
// ...
})
const useCartStore = defineStore('cart', {
// ...
})
export default {
computed: {
// 请注意,我们没有传递数组,只有一个商店一个接一个,每个商店都可以作为其 id + 'Store' 访问
...mapStores(useCartStore, useUserStore)
},
methods: {
async buyStuff() {
// use them anywhere!
if (this.userStore.isAuthenticated()) {
await this.cartStore.buy()
this.$router.push('/purchased')
}
},
},
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
默认情况下,Pania 会在每个商店的 id
中添加"Store"
后缀。 您可以通过调用 setMapStoreSuffix()
来自定义此行为:
js
import { createPinia, setMapStoreSuffix } from 'pinia'
// 完全去掉后缀:this.user, this.cart
setMapStoreSuffix('')
// this.user_store, this.cart_store (也可以)
setMapStoreSuffix('_store')
export const pinia = createPinia()
1
2
3
4
5
6
7
2
3
4
5
6
7
TypeScript #
默认情况下,所有地图助手都支持自动完成,你不需要做任何事情。 如果您调用 setMapStoreSuffix()
来更改 "Store"
后缀,您还需要将其添加到 TS 文件或您的 global.d.ts
文件中的某个位置。 最方便的地方是调用 setMapStoreSuffix()
的地方:
ts
import { createPinia, setMapStoreSuffix } from 'pinia'
setMapStoreSuffix('') // 完全删除后缀
export const pinia = createPinia()
declare module 'pinia' {
export interface MapStoresCustomization {
// 将其设置为与上面相同的值
suffix: ''
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
WARNING
如果您使用的是 TypeScript 声明文件(如 global.d.ts
),请确保在其顶部使用 import 'pinia'
以公开所有现有类型。