Vue Js中的复选框数组

Kyl*_*lie 4 javascript vue.js vuejs2

我有一个复选框数组,它们来自存储所有系统设置的主系统对象。(称为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>
Run Code Online (Sandbox Code Playgroud)

小智 17

<input type="checkbox" v-model="userRoles" :true-value="[]" :value="resource.role_name">
Run Code Online (Sandbox Code Playgroud)

你应该添加:true-value="[]".


Dob*_*leL 14

此行为在Checkbox绑定文档中有很好的记录。

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

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',
      }
    ]
  }
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)