如何将单选按钮绑定到 vuex 商店?

How to bind radio buttons to a vuex store?

我想将一组单选按钮的值单向绑定到我的模型,并在发生变化时更新 vuex 存储。不幸的是,这似乎没有在任何地方记录。任何帮助将不胜感激。

双向绑定的工作方式如文档所述:

<input type="radio" name="info-source" value="1" id="info-source-1" v-model="infoSource">
<label for="info-source-1">TV</label>
<input type="radio" name="info-source" value="2" id="info-source-2" v-model="infoSource">
<label for="info-source-2">Social media</label>

但是 vuex 在这种情况下开始抱怨 Do not mutate vuex store state outside mutation handlers

如警告所述,您不能在变异方法之外修改 Vuex 状态对象的值。

您可以创建一个计算 属性,它具有 get / set 方法来引用/更新 Vuex 存储中相关数据的状态。

这是一个简单的例子:

const store = new Vuex.Store({
  state: {
    gender: 'female',
  },
  mutations: {
    SET_GENDER(state, gender) {
      state.gender = gender;
    }
  }
});

new Vue({
  el: '#app',
  store,
  computed: {
    gender: {
      get() {
        return this.$store.state.gender;
      },
      set(value) {
        this.$store.commit("SET_GENDER", value);
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.min.js"></script>
<div id="app">
  <input type="radio" name="gender" value="male" v-model="gender">Male<br>
  <input type="radio" name="gender" value="female" v-model="gender">Female<br>
  <input type="radio" name="gender" value="other" v-model="gender">Other<br>
  Vuex store value: {{ $store.state.gender }}<br>
  Computed property value: {{ gender }}
</div>

blogpost 让我走上了正确的轨道。我想到的解决方案是:

<input type="radio" name="info-source" value="1" 
       :checked="infoSource === 1" @change="updateInfoSource(1)">

使用 updateInfoSource 方法提交到商店。

有关完整示例,请查看以下 post:How to bind radio buttons to a vuex store?