首页 > 解决方案 > Vue Js中的复选框数组

问题描述

我有一组复选框,来自存储所有系统设置的主系统对象。(称为 getSystem{})。

在这种形式中,我正在访问一个用户,该用户具有一组角色 []。如何对照 getSystem.user_roles 检查这个角色数组?

我知道如何正常进行,显然是在 javascript 中。但是我会明智地在复选框输入 Vue.js 中添加什么?

    <b-form-group>
      <label for="company">Email Address</label>
      <b-form-input type="text" id="email" v-model="user.email" placeholder="Enter a valid e-mail"></b-form-input>
    </b-form-group>
    // Here i can do user.roles to get the array of roles.
    // What can I do to loop through the roles and check the box if it exists in the user roles??
    <b-form-group v-for="resource, key in getSystem.user_roles" v-if="getSystem.user_roles">
       <label>{{resource.role_name}}</label>
       <input type="checkbox" [ what do I put here to compare against user.roles, and check the box if exists??]  > 
    </b-form-group>

标签: javascriptvue.jsvuejs2

解决方案


Checkbox binding Docs中有详细记录此行为。

这是一个模拟你的逻辑的小例子

new Vue({
  el: '#app',
  data: {
    user: {
      email: 'test@test.com',
      roles: [{id: 1, name: 'Client'}]
    },
    roles: [
      {
        id: 1,
        name: 'Client',
      },
      {
        id: 2,
        name: 'Admin',
      },
      {
        id: 3,
        name: 'Guest',
      }
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="app">
  <div>
    <label>Email</label>
    <input type="text" v-model="user.email" />
  </div>
  <div v-for="role in roles" :key="role.id">
    <label>{{role.name}}</label>
    <input type="checkbox" v-model="user.roles" :value="role"/>
  </div>
  
  <p>User's selected roels</p>
  {{user.roles}}
</div>


推荐阅读