翻译进度
2
分块数量
0
参与人数

4.4. 脱离 setup() 的用法

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。

翻译时请参照官方英文原版文档


Usage without setup()

Pinia can be used even if you are not using the composition API (if you are using Vue <2.7, you still need to install the @vue/composition-api plugin though). While we recommend you give the Composition API a try and learn it, it might not be the time for you and your team yet, you might be in the process of migrating an application, or any other reason. There are a few functions:

Giving access to the whole store

If you need to access pretty much everything from the store, it might be too much to map every single property of the store... Instead you can get access to the whole store with mapStores():

import { mapStores } from 'pinia'

// given two stores with the following ids
const useUserStore = defineStore('user', {
  // ...
})
const useCartStore = defineStore('cart', {
  // ...
})

export default {
  computed: {
    // note we are not passing an array, just one store after the other
    // each store will be accessible as its id + 'Store'
    ...mapStores(useCartStore, useUserStore)
  },

  methods: {
    async buyStuff() {
      // use them anywhere!
      if (this.userStore.isAuthenticated()) {
        await this.cartStore.buy()
        this.$router.push('/purchased')
      }
    },
  },
}

By default, Pinia will add the "Store" suffix to the id of each store. You can customize this behavior by calling the setMapStoreSuffix():

import { createPinia, setMapStoreSuffix } from 'pinia'

// completely remove the suffix: this.user, this.cart
setMapStoreSuffix('')
// this.user_store, this.cart_store (it's okay, I won't judge you)
setMapStoreSuffix('_store')
export const pinia = createPinia()

TypeScript

By default, all map helpers support autocompletion and you don't need to do anything. If you call setMapStoreSuffix() to change the "Store" suffix, you will need to also add it somewhere in a TS file or your global.d.ts file. The most convenient place would be the same place where you call setMapStoreSuffix():

import { createPinia, setMapStoreSuffix } from 'pinia'

setMapStoreSuffix('') // completely remove the suffix
export const pinia = createPinia()

declare module 'pinia' {
  export interface MapStoresCustomization {
    // set it to the same value as above
    suffix: ''
  }
}

:::warning If you are using a TypeScript declaration file (like global.d.ts), make sure to import 'pinia' at the top of it to expose all existing types. ::

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

thebestxt
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~