Answer the question
In order to leave comments, you need to log in
Ability to select multiple categories Vue JS?
Good day!
There is a list on the site that looks like this:
The data is returned in JSON when requested to the same server and then rendered in the Vue component.
<div class="categories">
<a href="#"
class="category"
v-for="(category, id) in categories"
:class="tagClass(category.id)"
@click="selectCategory(category)"
>
{{ category.name }}
</a>
<a href="#" class="category save" @click="saveCategories()">Сохранить</a>
</div>
<script>
export default {
data: function(){
return {
categories: [],
chosen: []
}
},
created: function(){
axios.post('get-categories')
.then(({data}) => {
for(var i = 0; i < Object.keys(data).length; i++){
this.categories.push(JSON.parse(JSON.stringify(data))[i]);
}
});
axios.post('user-categories')
.then(({data}) => {
for(var i = 0; i < Object.keys(data).length; i++){
this.chosen.push(JSON.parse(JSON.stringify(data))[i]);
}
});
},
methods: {
selectCategory(cat){
if(this.chosen.includes(cat.id)){
const index = this.chosen.indexOf(cat.id);
if(index >= -1){
this.chosen.splice(index, 1);
}
}else{
this.chosen.push(cat.id);
}
},
tagClass(id) {
const isSelected = this.chosen.includes(id);
return {
'active': isSelected,
'none': !isSelected
}
},
saveCategories() {
axios.post('add-categories', {categories: this.chosen})
.then(({data}) => {
console.log(data);
});
}
}
}
</script>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question