Checkbox 在Vue中,如何根据条件取消复选框?

Checkbox 在Vue中,如何根据条件取消复选框?,checkbox,vue.js,vuejs2,v-model,Checkbox,Vue.js,Vuejs2,V Model,我希望始终至少选中一个复选框,但我混合了v-model和:checked的概念 报告说: v-model将忽略初始的值,选中的或选中的属性 在任何表单元素上都可以找到。它将始终处理Vue实例数据 作为真理的源泉 我可以阻止我的模型被修改,但我不能阻止复选框被选中 一些代码: 模板 preventifilessthanone已选中处理程序 有没有停止本机复选框传播的方法?尝试在单个选中的复选框上使用禁用: <div class="wrapper" v-for="(s, id) in user

我希望始终至少选中一个复选框,但我混合了
v-model
:checked
的概念

报告说:

v-model
将忽略初始的
选中的
选中的
属性 在任何表单元素上都可以找到。它将始终处理Vue实例数据 作为真理的源泉

我可以阻止我的模型被修改,但我不能阻止复选框被选中

一些代码:

模板

preventifilessthanone已选中
处理程序


有没有停止本机复选框传播的方法?

尝试在单个选中的复选框上使用
禁用

<div class="wrapper" v-for="(s, id) in userOutputSeries" :key="id">
  <input type="checkbox" :id="id" :value="id"
      :disabled="(s.active && numberOfChecked == 1) ? disabled : null"
      @change="preventIfLessThanOneChecked" :checked="s.active">
  <label :for="id">{{ s.display }}</label>
</div>

{{s.display}

您应该使用
v-model
而不是
:checked
,这样对
userOutputSeries
数据属性的更改将反映在复选框输入中

然后,将
s
引用从
v-for
传递给该方法,并将该对象的
active
属性设置为
true
,如果没有
active
复选框:

newvue({
el:“#应用程序”,
数据(){
返回{
userOutputSeries:{
傅:{
显示:“真棒的福”,
主动:正确
},
酒吧:{
显示:“我的酒吧”,
活动:错误
}
}
}
},
方法:{
防泄漏检查(项目){
如果(项目激活){
返回;
}
让items=Object.values(this.userOutputSeries);
如果(!items.find(i=>i.active)){
item.active=true;
}
}
}
})

{{s.display}

在@thanksd给出的上述答案中,我的复选框保持未选中状态。 所以我在写我的解决方案

这是我的循环语句,根据您的文件更改变量名

v-for="column in tableColumns"
这是我的输入(如果visible为true,则选中复选框)


我被困在阻止事件的发生而不是考虑数据。。。谢谢我将结合@thanksd answer使用disabled属性来添加一些额外的样式。你的解决方案也在起作用。谢谢Tnx很多,这应该是可以接受的答案,因为当执行取消检查时,但实际地将v模型值更改回“true”,复选框将忽略这一点,并保持未检查状态,即使认为模型实际上是true。当您希望始终取消选中一个复选框时,可能会发生这种行为。只有这个“event.target.checked”魔法对tnx有很大帮助。另一种方法是在最后一次取消选中复选框时实际隐藏复选框,这样用户就不能再这样做了
preventIfLessThanOneChecked (event) {
  // I don't update the model so it stay at the same state
  // But only need to count the active series and do what we want.
  console.log(event.target.value, event.target.checked)
}
<div class="wrapper" v-for="(s, id) in userOutputSeries" :key="id">
  <input type="checkbox" :id="id" :value="id"
      :disabled="(s.active && numberOfChecked == 1) ? disabled : null"
      @change="preventIfLessThanOneChecked" :checked="s.active">
  <label :for="id">{{ s.display }}</label>
</div>
v-for="column in tableColumns"
<input type="checkbox" v-model="column.visible" @change="event => visibleColumnsChanged(column, event)">
visibleColumnsChanged: function(column, event){
  if (column.visible) {
    return;
  }

  if(! this.tableColumns.find(c => c.visible)){
    column.visible = true;

    event.target.checked = true;
  }
}