I
I
Insane062019-04-21 14:56:12
Laravel
Insane06, 2019-04-21 14:56:12

Ability to select multiple categories Vue JS?

Good day!
There is a list on the site that looks like this:
5cbc590f7323b297574792.png
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>

vue script:
<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>

The first time the user selects multiple categories and saves them. Accordingly, you need to display them already active. How to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arthur, 2019-04-21
@ART_CORP

If you understand the task correctly, you need this https://laravel.com/docs/5.8/eloquent-relationship...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question