W
W
WebDev2019-06-18 14:51:22
Vue.js
WebDev, 2019-06-18 14:51:22

Why sorting an array hangs the page in Vue?

Please tell me what could be the problem with this code:

<div v-for="event in sortedEvents">

</div>

<script>
...
computed: {
    sortedEvents() {
            return this.events.sort((e1, e2) => {
                return e1.order - e2.order;
            });
    }
}
...
</script>


The page freezes on this code. events is an array of 5 elements, the order property is correct for all of them.

UPD:
events is an array that is loaded in the parent and passed through props. If you add the stub of this array to data, then everything works.

UPD2:
If sortedEvents is moved to data and filled in created, then everything works.

UPD3:
If sortedEvents in computed is replaced with this code, then everything works too

computed: {
            sortedEvents() {
                let array = JSON.parse(JSON.stringify(this.events));

                array.sort((e1, e2) => {
                    return e1.order - e2.order;
                });

                return array;
            },
}

That is, the problem is somehow related to changes in this.events

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Severn101, 2019-06-19
@Severn101

Here is an infinite loop.
The sort method modifies the events array. Vue sees the changes and re-runs the sortedEvents calculation.
You have already been correctly advised, use watch, or make a copy of the events array in computed and sort it already.

A
Alexander Drozdov, 2019-06-18
@bagzon

You need to hang a watch on events, and when triggered, execute the array sorting method, and here, because of a bunch of observers, it lags.
Plus, most likely there should be an error, because the sort function changes the array being sorted, and since parent props this.events cannot be changed in child ones, then there will be an error.

R
Redrik_Shuhart, 2019-06-19
@Redrik_Shuhart

We have already noted above that you have an infinite loop.
Replace
on the

let array = [...JSON.parse(JSON.stringify(this.events))]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question