From: reslear Date: Wed, 29 Sep 2021 12:28:42 +0000 (+0300) Subject: docs: add getters method-style Access example [skip ci] (#633) X-Git-Tag: pinia@2.0.0-rc.10~10 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=228c664c0f7284cc4e8a3b705c11be1c51f01dbe;p=thirdparty%2Fvuejs%2Fpinia.git docs: add getters method-style Access example [skip ci] (#633) * docs: add getters method-style Access example from https://github.com/posva/pinia/issues/342 * Apply suggestions from code review Co-authored-by: Eduardo San Martin Morote --- diff --git a/packages/docs/core-concepts/getters.md b/packages/docs/core-concepts/getters.md index 130c680a..292a3b56 100644 --- a/packages/docs/core-concepts/getters.md +++ b/packages/docs/core-concepts/getters.md @@ -79,6 +79,52 @@ export const useStore = defineStore('main', { }) ``` + +## Passing arguments to getters + +_Getters_ are just _computed_ properties behind the scenes, so it's not possible to pass any parameters to them. However, you can return a function from the _getter_ to accept any arguments: + +```js +export const useStore = defineStore('main', { + getters: { + getUserById: (state) => { + return (userId) => state.users.find((user) => user.id === userId) + }, + }, +}) +``` + +and use in component: + +```vue + + + +``` + +Note that when doing this, **getters are not cached anymore**, they are simply functions that you invoke. You can however cache some results inside of the getter itself, which is uncommon but should prove more performant: + +```js +export const useStore = defineStore('main', { + getters: { + getActiveUserById(state) { + const activeUsers = state.users.filter((user) => user.active) + return (userId) => activeUsers.find((user) => user.id === userId) + }, + }, +}) +``` + ## Accessing other stores getters To use another store getters, you can directly _use it_ inside of the _getter_: