[英]Using V-for in checkboxes in vue
使用 axios>>vue JS>>spring boot,我能夠毫無問題地列出值並將它們保存到數據庫中。 我的問題我只想在選中復選框或在 Vue JS 中為 true 時觸發我的保存方法。 在我的例子中,我在我的復選框中使用了 v-on:change,但每次我單擊該復選框時都會調用該方法。 有沒有一種方法可以僅在選中復選框(true)時調用我的保存方法。 我的數據庫中的數據如圖所示顯示
這是我的代碼:
<thead>
<tr> <th>ID</th>
<th>Subject Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="item in subjectData">
<td>{{item.id}}</td> <td>{{item.subjectName}}</td>
<td><input type="checkbox" v-on:change.prevent="saveMarks(item)" /></td>
</tr>
</tbody>
</table>
</div>
<script>
var subjectStudentsVM=new Vue({
el:"#subjectStudentsSelection",
data:function(){
return {
id: '',
studid:'',
subjectData:Array(),
}
},
created:function (){
this.getAllSubjects();
},
methods:{
saveMarks: function(item) {
var self=this;
axios({
method:"POST",
url:"/Student/"+this.studid+"/"+item.id,
// url:"/Student/2/2",
headers: {
'content-type': 'application/json',
},
data:{
}
})
},
getAllSubjects:function(){
var self=this;
axios.get("/Subject/list/").then(function (response) {
this.subjectData = response.data;
}.bind(this)).catch(function (error) {
console.log('Error while fetching subject data: ' + error)
})
},
}
})
您需要在函數saveMarks
中檢查復選框的狀態,然后才保存。
像這樣:
saveMarks: function(item,event) {
var self=this;
if (event.target.checked === true){
axios({
method:"POST",
url:"/Student/"+this.studid+"/"+item.id,
// url:"/Student/2/2",
headers: {
'content-type': 'application/json',
},
data:{
}
})
console.log("record saved");
}else{
console.log("record not saved");
//return
}
您可以執行以下操作:
<template>
<label>
<input
ref="input"
type="checkbox"
:checked="value"
@input="onInput">
</label>
</template>
<script>
export default {
name: 'InputCheckbox',
props: {
value: {
type: Boolean,
default: true,
},
},
methods: {
onInput() {
const status = !!this.$refs.input.checked;
this.$emit('input', status);
this.$emit('change', status);
if(status) {
// do something in here (like axios calls)
}
},
},
};
</script>
這是一個自定義復選框vue組件,我在項目中使用了它,而且它絕不會錯過它的工作。 我希望這有助於跟蹤變更事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.