Blair
Blair

Reputation: 3751

Vuex computed property not updating v-show

I have a simple Vuex module with one object: selectedEvent.

I am able to update my selected event using:

  <Event :event="selectedEvent" />

However, I am unable to update the visibility of this property using a computed getter defined in the module:

  <Event :event="selectedEvent" v-show="isEventSelected" />

My computed values in App.js:

  computed: mapState({
    selectedEvent: state => state.events.selectedEvent,
    isEventSelected: state => state.events.isEventSelected
  })

I'm aware that Vue has trouble observing some Object/ Array changes, so I have used Vue.set in my mutation. I have also attempted to move v-show inside the Event component, with no success.

If I move the getter logic inside the v-show, it works fine (however it's messy), e.g.:

<Event :event="selectedEvent" v-show="selectedEvent.hasOwnProperty('id')" />

I'm fairly new to Vue - What am I missing here?

store/modules/events.js:

import { EVENT_SELECT } from "./types";
import Vue from "vue";

const state = {
  selectedEvent: {}
};

const getters = {
  selectedEvent: state => {
    return state.selectedEvent;
  },
  isEventSelected: state => {
    return state.selectedEvent.hasOwnProperty("id");
  }
};

const actions = {
  setSelectedEvent({ commit }, selectedEvent) {
    commit(EVENT_SELECT, selectedEvent);
  }
};

const mutations = {
  [EVENT_SELECT](state, selectedEvent) {
    Vue.set(state, "selectedEvent", selectedEvent);
  }
};

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
};

App.vue:

<template>
  <div id="app">
    <b-container>
      <Calendar />
      <Event :event="selectedEvent" v-show="selectedEvent.hasOwnProperty('id')"/>
    </b-container>
  </div>
</template>

<script>
import Calendar from "./components/Calendar.vue";
import Event from "./components/Event.vue";
import { mapState } from "vuex";

export default {
  name: "app",
  components: {
    Calendar,
    Event
  },
  computed: mapState({
    selectedEvent: state => state.events.selectedEvent,
    isEventSelected: state => state.events.isEventSelected
  })
};
</script>

Upvotes: 0

Views: 1462

Answers (1)

Phil
Phil

Reputation: 164798

In your store, isEventSelected is a getter, not a state property so you should use mapGetters, eg

import { mapState, mapGetters } from 'vuex'

// snip

computed: {
  ...mapState('events', ['selectedEvent']),
  ...mapGetters('events', ['isEventSelected'])
}

Upvotes: 3

Related Questions