我有来自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,则一切正常。如何使它具有多个复选框?
答案 0 :(得分:2)
我创建了基本的工作示例
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>
答案 1 :(得分:-1)
最好使用:value
而不是v-model
,并通过发送事件(用于访问复选框的值)和属于该选项的@change方法来调用函数。此复选框。
<tr v-for="(option, index) in options">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="toggle" :value="option.value" @change="toggleOption($event, option)">
<label class="custom-control-label" for="toggle">{{ option.value }}</label>
</div>
在该方法中,您将事件和选项作为参数接收。然后,您可以使用复选框的值(由event.target.checked
收集)访问选项的值和ID。
toggleOption(event, option) {
let app = this;
app.loading = true;
option.value = event.target.checked;
axios.patch('/apiendoint' + option.id, option)
.then(function (resp) {
app.loading = false;
})
.catch(function (resp) {
});
}
之所以使用@change是因为有时可以触发@input