Multiple Select Vue.js And Computed Property
I'm using Vue.js 2.0 and the Element UI library. I want to use a multiple select to attribute some roles to my users. The list of all roles available is received and assigned to av
Solution 1:
I agree mostly with @wostex answer, but he doesn't give you the userRoles
property back. Essentially you should swap computedRoles
and userRoles
. userRoles
becomes a computed property and computedRoles
is a data property. In my update, I changed the name of computedRoles
to selectedRoles
.
varMain = {
data() {
return {
availableRoles: [{
id: 1,
name: 'Admin'
}, {
id: 2,
name: 'Power User'
}, {
id: 3,
name: 'User'
}],
selectedRoles:[1,2]
}
},
computed : {
userRoles(){
returnthis.availableRoles.reduce((selected, role) => {
if (this.selectedRoles.includes(role.id))
selected.push(role);
return selected;
}, [])
}
}
}
varCtor = Vue.extend(Main)
newCtor().$mount('#app')
And here is the fiddle.
Solution 2:
Check the solution: jsfiddle
The caveat here is that computed properties are getters mainly. You can define setter for computed property, but my approach is more vue-like in my opinion.
In short, instead of v-model
on computed set v-model
for data property.
Full code:
<script src="//unpkg.com/vue/dist/vue.js"></script>
<scriptsrc="//unpkg.com/element-ui/lib/index.js"></script><divid="app"><template><el-selectv-model="ids"multipleplaceholder="Select" @change="logit()"><el-optionv-for="item in availableRoles":label="item.name":value="item.id"></el-option></el-select></template></div>varMain = {
data() {
return {
availableRoles: [{
id: 1,
name: 'Admin'
}, {
id: 2,
name: 'Power User'
}, {
id: 3,
name: 'User'
}],
userRoles: [{'id':1, 'name':'Admin'}, {'id':3, 'name':'User'}],
ids: []
}
},
mounted() {
this.ids = this.userRoles.map(role => role.id);
},
methods: {
logit: function() {
console.log(this.ids);
}
}
}
varCtor = Vue.extend(Main)
newCtor().$mount('#app')
Post a Comment for "Multiple Select Vue.js And Computed Property"