vue.js - 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,则一切正常。如何使它与多个复选框一起工作?
解决方案
我创建了基本的工作示例
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>
推荐阅读
- javascript - 反馈循环三.js
- python - if 工作正常但 elif 抛出错误
- android - 致命异常:java.lang.StackOverflowError 堆栈大小 8MB android.view.View.hasIdentityMatrix
- c# - 使用 Newtonsoft 将 Json 反序列化为 C# 中的对象列表
- android - 父视图高度为 match_parent 但接受来自(上一屏)视图下的点击
- java - 在后台启动服务时类引用 null
- arrays - 注入安全的 Postgres 批量插入/更新。也许是一个需要数组的函数?
- intellij-idea - 安装 IntelliJ IDEA 后从控制台运行一个简单的 hello world
- python - DataFrame 上的 Scipy 最小化优化逐行
- tensorflow - 如何使用 Tensorflow 或 GBM 调整模型以获得罕见的二元结果