繁体   English   中英

使用 Vue.js 将复选框设置为选中状态

[英]Setting a checkbox as checked with Vue.js

我一直在谷歌搜索和玩我知道的每一个组合,但我无法让我的复选框被初始化为选中状态。

例子:

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

我可以做些什么来初始设置复选框的选中状态?

要设置复选框的值,您需要将 v-model 绑定到一个值。 如果值是真实的,复选框将被选中。 在这种情况下,您正在迭代modules ,并且每个module都有一个checked的属性。

以下代码将复选框与该属性绑定:

<input type="checkbox" v-model="module.checked" v-bind:id="module.id">

请注意,我删除了v-bind:value="module.id" 你不应该在同一个元素上使用v-modelv-bind:value 来自 vue 文档

 <input v-model="something">

只是语法糖:

 <input v-bind:value="something" v-on:input="something = $event.target.value">

因此,通过使用v-modelv-bind:value ,您实际上最终会得到v-bind:value两次,这可能会导致未定义的行为。

假设您想将一个道具传递给子组件,并且该道具是一个布尔值,它将确定复选框是否被选中,那么您必须将布尔值传递给v-bind:checked="booleanValue"或更短的方法:checked="booleanValue" ,例如:

<input
    id="checkbox"
    type="checkbox"
    :value="checkboxVal"
    :checked="booleanValue"
    v-on:input="checkboxVal = $event.target.value"
/>

这应该可以工作,并且复选框将显示具有当前布尔状态的复选框(如果选中,则未选中)。

在 v-model 中,属性的值可能不是严格的布尔值,并且复选框可能不会“识别”该值是选中/未选中。 VueJS 中有一个巧妙的功能可以转换为 true 或 false:

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

我有类似的要求,但我不想使用v-model在父组件中拥有状态。 然后我得到了这个工作:

<input
  type="checkbox"
  :checked="checked"
  @input="checked = $event.target.checked"
/>

为了从父级传递值,我对此进行了一些小改动,它可以工作。

<input
  type="checkbox"
  :checked="aPropFrom"
  @input="$emit('update:aPropFrom', $event.target.checked)"
/>

 <input v-if = "module.checked == true" checked type="checkbox" > <input v-else-if = "module.checked == false" type="checkbox" >

我已经使用 v-if 和 v-else-if 解决了这个问题

我遇到了这个问题并且在几个小时内无法找到解决方法,直到我意识到我错误地prevented本地事件的发生:

<input type="checkbox" @click.prevent="toggleConfirmedStatus(render.uuid)"
    :checked="confirmed.indexOf(render.uuid) > -1"
    :value="render.uuid"
/>

@click处理程序中删除.prevent解决了我的问题。

我同时使用隐藏和复选框类型输入来确保将 0 或 1 提交到表单。 确保字段名称相同,因此只有一个输入将发送到服务器。

<input type="hidden" :name="fieldName" value="0">
<input type="checkbox" :name="fieldName" value="1" :checked="checked">

就我而言,我有一个简单的布尔类型,所以我所做的是:

在我的 html 中: <input type="checkbox" :checked="article.is_public" :value="article.is_public" @change="updateIsPublic($event.target.checked)">

methods: {
  updateIsPublic (e) {
      this.$store.commit('articles/UPDATE_IS_PUBLIC', e);
    },
}

店铺

 UPDATE_IS_PUBLIC(state, value) {
    state.article.is_public = value;
  }

对于 bootstrap vue,如果 value 为“1”,则 value="1" 和“0” unchecked-value="0"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM