在Vue中的复选框中使用V-for

时间:2019-12-01 08:44:27

标签: javascript vue.js axios

我可以使用axios >> vue JS >> spring boot列出值并将其保存到数据库中,而不会出现任何问题。我的问题是我只想在Vue JS中选中复选框或为true时才触发保存方法。就我而言,我在复选框中使用v-on:change,但是每次我单击复选框时都会调用该方法。有没有一种方法可以仅在选中复选框(true)时调用我的save方法。 我从数据库中获得的数据显示如下所示

enter image description here

这是我的代码:

      <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)
          })
    },
}
})

2 个答案:

答案 0 :(得分:0)

您需要在函数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

                }

答案 1 :(得分:0)

您可以执行以下操作:

<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组件,我在项目中使用了它,而且它不会错过任何工作。我希望这有助于跟踪变更事件。