【问题标题】:Vuejs - v-model with multiple checkboxesVuejs - 具有多个复选框的 v-model
【发布时间】:2019-01-18 16:16:47
【问题描述】:

我有来自 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,则一切正常。如何使它与多个复选框一起工作?

【问题讨论】:

  • 我觉得你打错了v-model="options.value"应该是v-model="option.value"
  • 哎呀,我的错,但这不能解决问题。
  • 您的&lt;tr&gt; 中缺少&lt;td&gt;...
  • 你能创建一个可重现的代码笔或类似的东西吗?目前还不太清楚您需要什么以及有什么问题。

标签: vue.js checkbox


【解决方案1】:

我创建了基本的工作示例

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>

【讨论】:

  • 这就是解决方案!谢谢! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
相关资源
最近更新 更多