首页 > 解决方案 > Vuejs - 具有多个复选框的 v-model

问题描述

我有来自 api 的动态选项列表:

       <tr v-for="(option, index) in options">
                <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="toggle" v-model="option.value" @click="toggleOption(option.id, index)">
                        <label class="custom-control-label" for="toggle">{{ option.value }}</label>
                </div>

方法:

 toggleOption(id, index) {
            let app = this;
            let option = this.options[index];
            app.loading = true;
            option.value = !option.value;
            axios.patch('/apiendoint' + id, option)
                .then(function (resp) {
                    app.loading = false;
                })
                .catch(function (resp) {

                });
        }

单击复选框时,所有复选框都会更改,如果只有一项来自 api,则一切正常。如何使它与多个复选框一起工作?

标签: vue.jscheckbox

解决方案


我创建了基本的工作示例

new Vue({
  el: '#app',
  data: {
    loading: false,
    options: [
      {id: 1, value: true},
      {id: 2, value: true},
      {id: 3, value: true},
    ]      
  },
  methods: {
    /*
      instead of passing `id` and `index`, just pass `option`
    */
    toggleOption(option) {
      let app = this;
      
      app.loading = true;
      option.value = !option.value;

      // REMOVE NEXT LINE to send ajax
      return;

      axios.patch('/apiendoint/' + option.id, option)
        .then(function (resp) {
          app.loading = false;
        })
        .catch(function (resp) {});
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">

  <table>
    <tr v-for="(option, index) in options">
      <td>
        <div class="custom-control custom-switch">
          <input
            :id="'toggle-'+option.id"
            type="checkbox"
            class="custom-control-input"
            v-model="option.value"
            @click="toggleOption(option)"
          >
          <label class="custom-control-label" :for="'toggle-'+option.id">
            {{ option.value }}
          </label>
        </div>
      </td>

    </tr>
  </table>
</div>


推荐阅读