设置一个复选框,如已通过Vue.js选中 [英] Setting a checkbox as checked with Vue.js

查看:44
本文介绍了设置一个复选框,如已通过Vue.js选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用谷歌搜索和了解我所知道的每种组合,但是我无法将我的复选框初始化为选中状态.

I have been googling and playing with every combination I know but I cannot get my checkboxes to be initialised as checked.

示例:

<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>

模块数据的示例:

[
    {
        "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?

推荐答案

要设置复选框的值,您需要将v模型绑定到一个值.如果该值为真,则将选中该复选框.在这种情况下,您要遍历 modules ,并且每个 module 都有一个 checked 属性.

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">


请注意,我删除了 v-bind:value ="module.id" .您不应在同一元素上使用 v-model v-bind:value .从vue 文档:


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">

因此,通过使用 v-model v-bind:value ,您实际上最终拥有 v-bind: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆