vuejs:如果我通过v模型获取复选框的值,但没有从数据库动态设置复选框。另一方面,如果我可以将chechbox设置为动态选中,但无法获取checked复选框的值。
通过此操作,我获得了已选中复选框的值,但未设置为动态选中
<li v-for="swv in appointment.switch_shift " >
<input type="checkbox" :value="swv.id" v-model="checkshifts"
@change="shiftSwitch()" />
<label > {{ swv.name}}</label>
</li>
----------------------------------------
data : {1: {id: 1, name: "Morning", active: true}, 2: {id: 2, name: "Afternoon", active: false},…}
如果使用以下代码对选中的设置复选框进行了动态检查,但无法获取选中复选框的值。
<li v-for="swv in appointment.switch_shift " >
<input type="checkbox" v-model="swv.active"
@change="shiftSwitch()" />
<label > {{ swv.name}}</label>
</li>
我希望这两个操作应该一起工作。谢谢
答案 0 :(得分:1)
首先,以这种方式动态更新数据库不是一个好主意,因为它是异步操作,并且如果有人在上一个更新过程之前多次选中/取消选中该复选框,则可能会导致大量并发问题,并且结果无法预测还没结束因此,您最好有一个特殊的按钮来在更新过程中在UI块中更新数据。
但是,如果您坚持要这样操作,那么我认为最好的方法是不为检查对象设置模型,而是以一种方式绑定它,然后单击直接在模型对象中切换它。像这样
<li v-for="swv in appointment.switch_shift " >
<input type="checkbox" :checked="swv.active"
@click.prevent = "shiftSwitch(swv)" />
<label > {{ swv.name}}</label>
</li>
和组件
...
methods:{
shiftSwitch:function(swv){
swv.active = !swv.active;
...
}
},
...
答案 1 :(得分:0)
是的,我解决了此问题。首先,从数据库中动态选中复选框,请参见下面的代码。
HTML
<li v-for="swv in appointment.switch_shift " >
<input class="js-small" type="checkbox" v-model="swv.active"
@change="shiftSwitch()" />
<label > {{ swv.name}}</label>
</li>
**Data**
appointment.switch_shift: {
1: {id: 1, name: "Morning", active: false}
2: {id: 2, name: "Afternoon", active: true}
3: {id: 3, name: "Evening", active: false}
}
see one thing when i checked any of checkbox of Morning , Afternoon, Evening then corresponds data row active become true like below
{id: 1, name: "Morning", active: true}
,然后取消选中{id:1,name:“ Morning”,active:false}
使用this.appointment.switch_shift的数据发布数据库中的更新。
方法
shiftSwitch:function(id){
axios.post(this.switchshiftroute , {'opd_id':this.opdid , 'shifts': this.appointment.switch_shift})
.then( (response)=>{
this.getAppointments();
console.log(response.data);
}).catch((error)=>{
console.log(error);
})
}