Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuex getter with argument written in Typescript

One can create a vuex store getter which takes a parameter argument as illustrated here: https://vuex.vuejs.org/en/getters.html

I'm using Typescript (https://github.com/hmexx/vue_typescript_starter_kit) to write my code, but I can't figure out how to write a getter that takes a parameter argument. ie, the following does not seem to work:

export function getItemById(state : State, id : Number) : MyItem | undefined     {
  if(id === undefined) {
    return undefined;
  }
  for(const item of state.items) {
    if(item.id === id) {
      return item;
    }
  }
  return undefined;
}

export default <GetterTree<State, any>> {
  getItemById
};
like image 592
Marek Krzeminski Avatar asked Dec 11 '22 09:12

Marek Krzeminski


1 Answers

based on vuex docs you can implement the following:

getters: {
  // ...
  getTodoById: (state, getters) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

in typescript you might try something like this:

export default {
  getItemById(state: State, getters: any) {
    return (id: number) => {
      return state.items.find(item => item.id === id);
    }
  }
}
like image 186
classicalConditioning Avatar answered Mar 05 '23 07:03

classicalConditioning