使用 Vue.js 将复选框设置为选中状态 [英] Setting a checkbox as checked with Vue.js
问题描述
我一直在谷歌上搜索并使用我知道的每个组合,但我无法将我的复选框初始化为选中状态.
示例:
<li v-for="模块中的模块"><label v-bind:for="module.id"><input type="checkbox" v-model="form.modules" v-bind:value="module.id" v-bind:id="module.id"><span>@{{module.name }}</span>标签>
模块数据示例:
<预><代码>[{身份证":1,"name": "业务",检查":真},{身份证":2,"name": "业务 2",检查":假},]我可以做些什么来初始设置复选框的选中状态?
要设置复选框的值,需要将 v-model 绑定到一个值.如果值为真,则复选框将被选中.在这种情况下,您正在迭代 modules
并且每个 module
都有一个 checked
属性.
以下代码将复选框与该属性绑定:
请注意,我删除了 v-bind:value=module.id"
.你不应该在同一个元素上使用 v-model
和 v-bind:value
.来自 vue 文档:><块引用>
只是语法糖:
因此,通过使用 v-model
和 v-bind:value
,您实际上最终拥有 v-bind:value
两次,这可能会导致未定义的行为.
I have been googling and playing with every combination I know but I cannot get my checkboxes to be initialised as checked.
Example:
<ul class="object administrator-checkbox-list">
<li v-for="module in modules">
<label v-bind:for="module.id">
<input type="checkbox" v-model="form.modules" v-bind:value="module.id" v-bind:id="module.id">
<span>@{{ module.name }}</span>
</label>
</li>
</ul>
An example of the modules data:
[
{
"id": 1,
"name": "Business",
"checked": true
},
{
"id": 2,
"name": "Business 2",
"checked": false
},
]
What can I do to initially set the checked status of the checkboxes?
To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules
and each module
has a checked
property.
The following code will bind the checkbox with that property:
<input type="checkbox" v-model="module.checked" v-bind:id="module.id">
Notice that I removed v-bind:value="module.id"
. You shouldn't use v-model
and v-bind:value
on the same element. From the vue docs:
<input v-model="something">
is just syntactic sugar for:
<input v-bind:value="something" v-on:input="something = $event.target.value">
So, by using v-model
and v-bind:value
, you actually end up having v-bind:value
twice, which could lead to undefined behavior.
这篇关于使用 Vue.js 将复选框设置为选中状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!