Vuex Getter With Parameters In TypeScript

 |  Vuex, TypeScript

When using Vuex with TypeScript, you typically use the @Getter decorator from the binding helpers package vuex-class. This is a more declarative approach over using this.$store.getters.*.

Vuex @Getter example

@Getter('books', { namespace: 'library' })
books!: Book[];

The getter above retrieves all books from the Vuex module library but what if you wanted to retrieve just a single book by it’s ID?


Method Style Getters

Vuex supports “method-style” getters which are getters that return a function with one or more parameters.

Vuex “method-style” getter example

...

const state: LibraryState = {
books: []
};

export const getters: GetterTree<LibraryState, RootState> = {
getBookById: (theState: LibraryState) => (id: string): Book | null => {
const book = theState.books.find(item => item.id === id);
return book || null;
}
};

...

In this example, the getter returns another function which accepts the book id argument and performs a query on the array in state to find the item. With this “method-style” getter in place, we can now get a handle to it from within a component via the @Getter decorator as follows.

@Getter decorator with argument example

@Getter('getBookById', { namespace: 'library' })
getBookById!: (id: string) => Book;

The getBookById function can now be called with the book id parameter to retrieve a single book from state.

mounted hook and route param example

export default class BookDetails extends Vue {
@Getter('getBookById', { namespace: 'library' })
getBookById!: (id: string) => Book;

book: Book | null = null;

mounted(): void {
const id = this.$route.params.id;
this.book = this.getBookById(id);
}
}