Vuex 与另一个互锁状态

Vuex interlocking state with another

我的状态与另一个状态相互依存,像这样:https://jsfiddle.net/MagicMagnate/1zufrspx/

const store = new Vuex.Store({
state: {
    checkedNames: ['Jack', 'Mike'],
    interlockedState : 'foo'

},
mutations: {
    updateChecked(state, payload) {
        state.checkedNames = payload
        state.interlockedState = 'bar' //trying to set the state but failed
    }
},
actions: {
    updateChecked({
        commit
    }, payload) {
        commit('updateChecked', payload)
    }
}
})

new Vue({
    store,
    el: '#example',
    //data: {interlockedState:'foo'},
    computed: {
        checkedNames: {
            get() {
                return this.$store.state.checkedNames
            },
            set(str) {
                this.$store.dispatch('updateChecked', str)
            }
        }
    }
})

只有 case 和 if else 更复杂, 我知道我不应该直接从 state 直接变异,但是我 运行 不知道如何为 state 分配一个新值来变异,这样这两个状态就不会相互关联。

您忘记为 interlockedState 设置计算值。

computed: {
  //...
  interlockedState(state) {
    return state.interlockedState
  }
}

这是更新后的 jsfiddle