Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable vuex getter caching?

Tags:

vue.js

vuex

I know you can disable caching in Vue computed properties by including a cache: false option. For example:

computed: {
  now: {
    cache: false,
    get() {
      return Date.now();
    }
  }
}

But I was wondering if this feature was available for Vuex getters

like image 475
feihcsim Avatar asked May 08 '18 15:05

feihcsim


1 Answers

To "disable" caching, you could take advantage of the fact that getters which are to be used as functions are not cached.

From the vuex docs

Note that getters accessed via methods will run each time you call them, and the result is not cached.

If you don't mind adding parenthesis (actually, calling functions) when accessing your non-cached property you could use something like this:

getters: {
  myNonCachedGetter: state => () => {
    // original getter body
  }
}

It is then used as myNonCachedGetter().

It turns out that the following doesn't work in newer versions of vuex.

However, if you would like it to look as a normal getter, you could wrap it into an function with invocation:

getters: {
  myNonCachedGetter: state => (() => {
    // original getter body
  })()
}

It does make the code look a bit harder to read, but it can be called as simple as myNonCachedGetter.

like image 89
Mak Avatar answered Oct 22 '22 01:10

Mak