不使用 setup() 的用法

即使不使用Composition API,也可以使用Pinia(如果您使用的是Vue 2,就需要安装@vue/composition-api插件)。虽然我们建议您尝试使用Composition API或者学习它,但现在对于您和您的团队可能还不是时候,您可能正在迁移应用程序的过程中,或者出于其他原因。这儿有几个可能帮到你函数:

获取整个 store 的访问权限

如果你需要访问store中几乎所有的内容,那么对于store的每个属性都需要做映射……相反,你可以通过mapStores()访问整个store

  1. import { mapStores } from 'pinia'
  2. // given two stores with the following ids
  3. const useUserStore = defineStore('user', {
  4. // ...
  5. })
  6. const useCartStore = defineStore('cart', {
  7. // ...
  8. })
  9. export default {
  10. computed: {
  11. // note we are not passing an array, just one store after the other
  12. // each store will be accessible as its id + 'Store'
  13. ...mapStores(useCartStore, useUserStore),
  14. }),
  15. },
  16. methods: {
  17. async buyStuff() {
  18. // use them anywhere!
  19. if (this.userStore.isAuthenticated()) {
  20. await this.cartStore.buy()
  21. this.$router.push('/purchased')
  22. }
  23. },
  24. },
  25. }

默认情况下,Pania将为所有storeid添加"Store"后缀。您也可以通过调用setMapStoreSuffix()来自定义:

  1. import { createPinia, setMapStoreSuffix } from 'pinia'
  2. // completely remove the suffix: this.user, this.cart
  3. setMapStoreSuffix('')
  4. // this.user_store, this.cart_store (it's okay, I won't judge you)
  5. setMapStoreSuffix('_store')
  6. export const pinia = createPinia()

TypeScript

默认情况下,所有的辅助函数都提供自动补全的功能,因此你不需要做任何事情。

如果您调用setMapStoreSuffix()更改"Store"后缀,您还需要将其添加到TS文件或global.d.ts文件中的某个地方。最方便的地方是您调用setMapStoreSuffix()的地方:

  1. import { createPinia, setMapStoreSuffix } from 'pinia'
  2. setMapStoreSuffix('') // completely remove the suffix
  3. export const pinia = createPinia()
  4. declare module 'pinia' {
  5. export interface MapStoresCustomization {
  6. // set it to the same value as above
  7. suffix: ''
  8. }
  9. }

WARNING 如果您使用TypeScript声明文件(如global.d.ts),请确保在它的头部引入'pinia'来公开所有现有的类型。