Vue - show loader while computed property being computed

217 Views Asked by At

EDIT - Found that sorting is quick, real issue is performance of rendering huge list, so already answered

pls explain to me, why this does nothing:

I have array of thousands of items, there is a button for sorting them by some prop (changes "sortBy" prop. Sorting items takes almost 2 seconds, at least that how long after the click does the list change. During computing (until new list displayed) i want to display some "Loading" element. Im not aware, byt maybe Vue has some app-wide state to tell something is being recomputed?

<div v-if="loading">Wait pliz</div>
<div @click="sortBy='ctg'">SortByCtg</div>
<div v-for="item in sortedRows">{{item.ctg}} , {{item.name}} .... </div>

and the computed prop fn:

data: function(){ 
   return { 
    'sortby': 'name', 
    'sortbyDir': 1, 
    'loading': false,
    'rows': [ {'name':'abc','ctg':'def'}, ...] 
  }
},
computed: {
    sortedRows: function(){
     this.loading = true; //  <<< should show element
     var sortby = this.sortby;
     var sortbyDir = this.sortbyDir;
     var sorted = this.rows;
     sorted = this.rows.sort(function(a, b) { 
      return sortbyDir * a[sortby].localeCompare(b[sortby]); 
     });
    this.loading = false; //  <<< hide element
    return sorted;
  }
},
...

but the "loading" element never shows. May it be sort is quick, and what is taking the time is the nodes generation itself? Then can i anyhow show the loader? Maybe somehow use next tick? I tried but with no result.

2

There are 2 best solutions below

5
PM_KLS On BEST ANSWER

Sorting is quick (few miliseconds), what really takes time is rendering the long list

3
Soresu On

"Sorting items takes almost 2 seconds" and "May it be sort is quick" are against each other, but you can't see the loading indicator in either of them. Usually, a sort finishes in some ms, you can barely see anything. Another possibility is if it runs for 2 seconds (slow algorithm or rendering thousands of rows on the page after sort), it blocks the main thread and you won't see any changes on the page.

Your code should work, but you shouldn't change data in computed. The sort method mutating the original array, and you change the loading variable. It can also run multiple times unnecessarily.