头图
This article records the use of el-autocomplete and two common problems

demand analysis

Suppose we have such a demand:

  • After the user enters the content in the input box, the associated suggestion option information is presented for the user to choose. For example, if the user enters the word "王", then all the information about "king" should be presented, what is "old king", "Wang Laoji" is all out, users click on the associated suggestion options, so that users can input quickly.
  • In the initial situation, when the user's input input box has the focus, at the same time, when the content in the input input box is not available, the user's previous search history is displayed.
  • When the user enters some text but the backspace is deleted one by one, that is, when the user deletes the text in the input box, that is, when the content of the input input box is empty, the history record is displayed again
At this time, using the el-autocomplete component can quickly solve our problem

Introduction to el-autocomplete attributes

fetch-suggestions attribute

The function is bound. The trigger condition of the function is when the input is entered, or after the user enters the box and enters the word, it will be triggered. Normally, there are two parameters of the callback function, namely queryString and cb. The value represented by the queryString parameter is the data value that the user fills in the input box, and cb refers to a function. Here is the usage of higher-order functions (currying), so I won’t go into details here. The cb function receives an array, what is in the array, and what is the drop-down box associated with the input input box, which corresponds to one by one. However, there is a fixed format requirement. Because there is a v-for loop instruction in the underlying code of el-autocomplete, the looped array is the array passed by the cb function, so the content of the array in the cb function is the content of the input suggested drop-down box

// html部分
:fetch-suggestions="querySearch"

// js部分
querySearch(queryString, cb) {
    cb([
        {value:"老王"},
        {value:"王老吉"} // 数组中的每一项都是一个对象,对象中必须要有value属性,否则不能显示,有没有别的属性不影响。原因是因为源码中定义的就是value字段
    ])
}
// 如果后端给的数据结构不是这种的结构的话,可以使用数组的filter或者map方法自己组装一下数据结构格式

The icons are as follows:

Fetch-suggestions can also pass multiple data, but it needs to be in the form of closures. This will be explained by an example later.

fetch-suggestions is used to search related data. The user enters the word "王" to obtain the associated option values of "Lao Wang" and "Wang Lao Kat". When the user selects Wang Lao Kat, if it is a search function, it needs to search. The specific information of Wang Laoji is available, so this time you need to use the select attribute of el-autocomplete

select attribute

The select binding is also a function method. When we click to select an option in the input input box associated with the drop-down box, we will get the value of the corresponding item in the drop-down box. This value can be passed to the backend to send a request to the backend to query the specific information of a selected piece of data.

// html部分
@select="handleSelect"

// js部分
handleSelect(item) { // 参数-选中的某一项
  console.log("拿到数据作为参数去向后端发请求",item);
}

trigger-on-focus attribute

The function of this attribute is to control whether fetch-suggestions are triggered when el-input gets focus. As long as fetch-suggestions is triggered, a request will be sent to the backend, and the input input box associated drop-down box (input suggestion list) will appear. The official definition is that the default is: trigger-on-focus=true, which is the input box input box one Get the focus, and the input suggestion list appears. This method of trigger-on-focus="true" can be used to obtain historical search data scenarios. After all, in the initial situation, the backend can provide historical data for users to choose.

Of course, if trigger-on-focus="false" is set, then the input suggestion list will not appear when the focus is initially obtained. After the user enters the text, the user will take the input in the input box to send the request. , Ask the backend for data.

The specific use depends on the specific needs.

Let's take a look at the renderings first, and then take a look at the code

Effect picture

Code attached

<template>
  <div id="box">
    <el-autocomplete
      :fetch-suggestions="querySearch"
      v-model="inputValue"
      @select="handleSelect"
      :debounce="0"
      :trigger-on-focus="true"
      clearable
      @clear="blurForBug()"
    ></el-autocomplete>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inputValue: "",
    };
  },
  methods: {
    //输入框获取焦点时调用的方法
    querySearch(queryString, cb) { // queryString是用户输入的想要查询的内容,cb是回调函数(可以发请求获取数据)
      console.log("如何触发", queryString, cb);
      if (queryString == "") {
        cb([{ value: "历史记录一" }, { value: "历史记录二" }]); // 当然这里的历史记录是后端返给我们的,应该为接口返回的数据
      } else {
        let apiResult = [
          {
            value: "老王",
          },
          {
            value: "王老吉",
          },
        ];
        // 这里我们模拟从后端的接口异步获取的数据
        setTimeout(() => {
          // cb([])    cb函数如果返回一个空数组的话,那个模糊搜索输入建议的下拉选项因为length为0就会消失了
          cb(apiResult);
        }, 500);
      }
    },
    // 选中输入框推荐的值的时候触发
    handleSelect(item) { // 参数
      console.log("拿到数据", item);
    },
    // 点击clearable清空小图标按钮以后,继续重新在输入框中输入数据,querySearch会触发,但是cb函数不会触发
    // 这样的话就会出现发请求了,也获取数据了,但是input框的输入建议下拉框不呈现在页面上的问题,所以解决方法就是
    // 只要用户点击了
    blurForBug(){
      document.activeElement.blur()
    }
  },
};
</script>

<style lang="less" scoped>
#box {
  width: 100%;
  height: 600px;
  box-sizing: border-box;
  padding: 50px;
}
</style>

common problem

Click the clearable button to enter the suggestion to be invalid

We will find that if the clearable attribute is added to the el-autocomplete component label, then when we enter the content, click the clearable button to clear the data entered in the input box, and when we re-enter the text, the request will be When triggered, the data returned to us by the backend is also obtained, but the data returned to us by the backend is not rendered on the page. It's as if the input is unresponsive. The more straightforward solution is that when the user clicks the clearable button, the input box that currently has the focus loses focus, returns to the original state, and everything starts again.

That is: Actively trigger the loss of focus, and solve the bug that @clear="blurForBug()"

Pass multiple parameters (using closures)

html part

<el-autocomplete
  v-model="inputValue"
  @select="handleSelect"
  :debounce="0"
  :trigger-on-focus="true"
  clearable
  @clear="blurForBug()"
 :fetch-suggestions="
      (queryString, cb) => {
        multipleFn(queryString, cb, index);
      }
    "
></el-autocomplete>

js part

multipleFn(queryString, cb, index) {
    console.log(queryString, cb, index)
}

Pay attention to the writing method of: fetch-suggestions in the above html part, here the writing method of closure is used, in this case, multiple parameters can be passed. Because if a function module has multiple el-autocomplete, in this case, we need to use v-for to loop it out. It may be necessary to pass item, index, etc. to the backend. At this time, it is necessary to pass multiple parameters Dropped, this time the problem can be solved by using the above closure method


水冗水孚
1.1k 声望589 粉丝

每一个不曾起舞的日子,都是对生命的辜负