Answer the question
In order to leave comments, you need to log in
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>
computed: {
sortedEvents() {
let array = JSON.parse(JSON.stringify(this.events));
array.sort((e1, e2) => {
return e1.order - e2.order;
});
return array;
},
}
Answer the question
In order to leave comments, you need to log in
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.
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.
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 questionAsk a Question
731 491 924 answers to any question