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>

原文由 Kylie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 683
1 个回答

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>

原文由 DobleL 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题