Search code examples
javascriptvue.jscheckboxvuex

Vue select all checkbox bad performance


I have a list objects displayed, each having a checkbox to select it. I also have a checkbox at the top to select the checkbox for every object, kinda like this (assume [ ] is a checkbox):

[ ] Select all

[ ] Object 1
[ ] Object 2
[ ] Object 3

The problem I have is when I have about 100 objects and clicking "Select all", the web page freezes for a good few seconds. There is also a search bar to filter the object, but I tested this by removing it and the performance is just as slow. Each object has a property selected so we know which object is selected. Below are some snippets of my code:

HTML:

<checkbox-input
  id="documentSelectAll"
  :model-value="operatingRows.length === 0 ? false : allSelected"
  @update:modelValue="allSelectPressed"  // Calls vuex function below
/>

---

<tr
  v-for="(row, index) in operatingRows"
  :key="index"
>
  <document-table-row
    :row-idx="index"
    :row-data="row"
    :fields="row.fields"
    :hidden-column-indices="hiddenColumnIndices"
    @toggleSelectedOnRow="toggleSelectedOnRow(row.id)"  // Calls vuex to select individual row
  />
</tr>

Computed properties:

operatingRows() {
    const showRow = (r) => {
      // Some search code, irrelevant here
    };
    return this.sorted.filter(showRow);  // 'sorted' comes from vuex
},
selectedRows() {
      return this.operatingRows.filter((r) => r.selected);
},
numSelected() {
      return this.selectedRows.reduce((prev, cur) => (cur.selected ? prev + 1 : prev), 0);
},
allSelected() {
      return this.numSelected === this.operatingRows.length;
},

Vuex store:

getters: {
    ...storeStateGetters,
    sorted: (state) => state.sorted,
},

---

mutations: {
    ...storeStateMutations,
    SET_ALL_SELECTED_ON_SORTED(state, isSelected) {
      state.sorted.map((r) => {
        const rn = r;
        rn.selected = isSelected;

        return rn;
      });
    },
},

I think it might be to do with the fact that there are too many computed properties? I tried removing them individually (and the associated code) but the performance still seems bad, thus I am not able to pin point the issue to any particular piece of code, rather I think it's to do with the architecture as a whole.

Any help appreciated.


Solution

  • Turns out it was because of the mutation. To fix this, the mutation code was moved to an action which calls a mutation to set the state of the sorted array.

    selectOnSorted: ({ commit, rootGetters }, isSelected) => {
      const selectedSorted = rootGetters['documents/sorted'].map((doc) => ({
        ...doc,
        selected: isSelected,
      }));
      commit('SET_SORTED', selectedSorted);
    },