Guardian
Guardian

Reputation: 399

VueJS Store pattern with get & set

I have a small store (following the state pattern on VueJS (not VUEX)).

It essentially looks like this

export default {
    get selectedPartner() {
        return localStorage.getItem('selectedPartner');
    },

    set selectedPartner(item) {

        localStorage.setItem('selectedPartner', item);
    },


    clearFilters() {
        localStorage.removeItem('selectedPartner');
    }
}

In my .vue component I am now trying to bind to it like so

    data: function() {
      return {
        // Other stuff here...
        selectedPartner: filterStore.selectedPartner,
      }
    },

Now, when it draws the component, the getter is actually properly called. When i change the value in the component, it does not update the store...

I do realise that doing it like this (in localStorage) is awfully close to VUEX. But chose for this approach to grasp state in its most simple form first, before getting into VUEX.

Many thanks

Upvotes: 1

Views: 714

Answers (1)

Shalom Peles
Shalom Peles

Reputation: 2632

Use computed instead of data:

computed: {
  selectedPartner: {
    get() { return filterStore.selectedPartner; },
    set(item) { filterStore.selectedPartner = item; }
  }
}

Upvotes: 1

Related Questions