首页 > 解决方案 > 在计算属性中使用 Vuex 状态打开模态,忽略更改,模态保持关闭

问题描述

我有以下代码可以将模态状态动态添加到 Vuex 商店并在整个应用程序中触发它们。即使状态发生变化,当我按下一个调度切换操作的按钮时,模态仍然隐藏。(对组件使用 quasar 框架)

零件

<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>

混音

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)
      }
    }
  }
}

店铺

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)
    }
  }
}

标签: javascriptvue.jsvuex

解决方案


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

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

推荐阅读