A
A
Alex2019-12-11 11:02:43
Vue.js
Alex, 2019-12-11 11:02:43

How to make a getter function?

The vuex store has an array of categories and an array of posts with the id of the category it belongs to:

{
  posts: [
    {id: 1, catId: 1, title: 'Foo'},
    //...
  ],
  categories: [
    {id: 1, title: 'CatFoo'}
  ]
}

As the application progresses, you need to get an array of posts for a certain category. How to do it via vuex getter? So that it caches the result and does not perform an array filter on each access.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2019-12-11
@Kozack

As a result, I wrote something like this:

getters: {
  getPostsByCategory(state) {
    const map = new Map();
    state.posts; // Необходимо чтобы геттер пересчитывался при изменении state.posts

    return (catId) => {
      if (map.has(catId)) {
        return map.get(catId);
      }

      let posts = state.posts.filter(p => p.catId === catId);
      map.set(catId, posts);


      return posts;
    };
  }
}

How it works:
A getter does not return a result, but a function. This function filters posts and caches the result through a closure. If any other component requires a list of posts of the same category, the eni will be returned from the cache.
When state.posts changes, this internal cache is cleared and the list of posts will be regenerated

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question