thatOneGuy
thatOneGuy

Reputation: 10622

How to rerun a Vuex Getter

Maybe I have misunderstood what a getter is in Vuex, but say I have a getter that gets the size of a DOM element, a div for example. I would do something like this :

const getters = {
  getContainerWidth (state) {
    return document.getElementById('main-content').clientWidth;
  }
}

Now when I start my app, all the getters seem to be run straight away. What if the div isn't available at startup? How do I rerun a getter?

I run the getter like this at the moment :

import store from '@/store'
store.getters['myModule/getContainerWidth']

I thought maybe this would work :

store.getters['myModule/getContainerWidth']()

But since store.getters is an object containing properties and values, and the values not being functions, I can't rerun them.

Any ideas?

Upvotes: 0

Views: 320

Answers (1)

Max Sinev
Max Sinev

Reputation: 6019

Getters should depend on state field to be reactive. It you want to observe clientWidth changes - it does not work.

If you want to use it like function then just return function from getter:

const getters = {
  getContainerWidth (state) {
    return () => {
       let container = document.getElementById('main-content');
       return container ? container.clientWidth : 0
    };
 }

}

and use it like getContainerWidth()

Upvotes: 1

Related Questions