javascript Vue Js 中的复选框数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50648407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checkbox array in Vue Js
提问by Kylie
I have an array of checkboxes, coming from a main system object where I store all system setting. (called getSystem{}).
我有一组复选框,来自我存储所有系统设置的主系统对象。(称为 getSystem{})。
In this form, Im accessing a User, which has an array of roles []. How can I check this array of roles, against the getSystem.user_roles?
在这种形式中,我访问一个用户,它有一个角色数组[]。如何根据 getSystem.user_roles 检查此角色数组?
I know how to do it normally, in javascript obviously. But what would I put in the checkbox input Vue.js wise?
我知道如何正常执行,显然是在 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>
回答by DobleL
This behavior is well documented on the Checkbox bindingDocs.
这种行为在Checkbox bindingDocs 中有详细记录。
Here a little example emulating your logic
这里有一个模拟你的逻辑的小例子
new Vue({
el: '#app',
data: {
user: {
email: '[email protected]',
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>

