Search code examples
javascriptvue.jsvuex

Using Vuex state in computed property to open modal, changes are ignored, modal stays closed


I have the following code to dynamically add modal states to the Vuex store and trigger them troughout my whole application. Even though the state changes, when I press a button which dispatches the toggle action, the modal stays hidden. (using quasar framework for components)

component

<template>
  <q-dialog v-model="status" persistent>
    <q-card>
      <q-card-actions align="right">
        <q-btn flat label="Abbrechen" color="dark" v-close-popup />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script>
  import modal from '../../mixins/modal'

  export default {
    name: 'DiscardSession',
    mixins: [modal]
  }
</script>

<style scoped>
</style>

mixin

export default {
  beforeCreate () {
    console.log('define modal')
    this.$store.dispatch('modal/define', this.$options.name)
  },
  computed: {
    status: {
      get () {
        console.log('getter triggered')
        return this.$store.getters['modal/status'][this.$options.name]
      },
      set () {
        console.log('setter triggered')
        this.$store.dispatch('modal/toggle', this.$options.name)
      }
    }
  }
}

store

export default {
  namespaced: true,
  state: {
    status: {}
  },
  getters: {
    status (state) {
      return state.status
    }
  },
  mutations: {
    DEFINE_STATUS (state, name) {
      state.status[name] = false
    },
    TOGGLE_STATUS (state, name) {
      state.status[name] = !state.status[name]
    }
  },
  actions: {
    define ({ commit, state}, name) {
      if (!(name in state.status)) commit('DEFINE_STATUS', name)
    },
    toggle ({ commit, state }, name) {
      commit('TOGGLE_STATUS', name)
    }
  }
}

Solution

  • It might be a reactivity problem. Can you try the following code?

    TOGGLE_STATUS (state, name) {
      state.status = {
        ...state.status,
        [name]: !state.status[name]
      }
    }