1. Scenario description

I don’t know if you have such experience, there are many options in the drop-down box, tens of thousands of options or even more. If all the data are rendered in the drop-down box at this time, the browser will be jammed and the experience will be particularly bad

The user might say that the element UI select has a remote method that supports remote search, so we can ask the server to support it. But sometimes that doesn’t always work

(1) Sometimes the server data is returned to us after calculation, which may not be very fast and the experience is not very good

(2) Sometimes there may only be thousands of data, and all rendering is not suitable, so it is not very good to keep dropping the interface

(3) Can it be solved only through the front end? If it can be solved, it will not reduce the work and pressure of the service end

2. Solutions

1) Segmental loading: do not load dropdown items. Click the dropdown box and then load it. All options are loaded in this case.

2) Hint: The element UI select has a filter-method method that can be used to filter dropdowns

Let’s say we have a drop-down box that selects users

<el-select
  v-model="userId"
  filterable
  :filter-method="userFilter"
  clearable>
  <el-option
    v-for="item in userList"
    :key="item.userId"
    :label="item.username"
    :value="item.userId"
  ></el-option>
</el-select>
Copy the code
userFilter(query = '') {
  let arr = this.allUserList.filter((item) => {
    return item.username.includes(query) || item.userId.includes(query)
  })
  if (arr.length > 50) {
    this.userList = arr.slice(0, 50)
  } else {
    this.userList = arr
  }
},
getUserWhiteList() {
  HttpRequest.post("/api/admin/community/getUserWhiteList").then(
    response => {
      this.allUserList = response.data.list;
      this.userFilter()
    }
  );
},
Copy the code

As shown above, we get the user list from the background, and through our own filtering, we only render 50 pieces of data at a time. No matter how much data there is, it also supports one variable for us, which takes up memory. Of course, the more data, the array traversal will be correspondingly slower, but this does not matter much.

We can filter not only the name, but also any item that we specify

Optimization: We can also optimize the above code, only if the array length exceeds 50 items, we will stop traversing