vue~el-autocomplete实现组件化

发布时间 2023-08-29 09:41:52作者: 张占岭

el-autocomplete核心参数

可以实现异步的数据拉取,从异步返回的数据中,选择需要的结果,并回显到文本框中。

fetch-suggestions

回调列表,异步的方式获取数据列表,显示在列表框中

@select

当选中某一项时,会触发这个方法,将数据获取到,这时,我们可以将数据回显,或者赋值给父页面上的元素,如果希望赋值父页面上v-model绑定的元素,可以通过v-model原理中说的,绑定input事件,将当前值进行传递即可。

实例代码

子组件代码

<template>
  <div>
    <el-autocomplete
      :fetch-suggestions="fetchSuggestions"
      v-model="dataValue"
      @select="handleSelect"
    >
      <template slot-scope="{ item }">{{ item.label }}</template>
    </el-autocomplete>
  </div>
</template>
<script>
export default {
  name: 'SearchLawfirmName',
  //allInfos是父组件传来的值,如果allInfos不是父组件传来的就不用这样写
  props: ["allInfos"],
  data() {
    return {dataValue: null}
  },
  methods: {
    fetchSuggestions(queryString, cb) {
      let results = this.allInfos;
      results = queryString
        ? results.filter(this.createFilter(queryString))
        : results;
      cb(results);
    },
    createFilter(queryString) {
      return (item) => {
        return item.value.toUpperCase().match(queryString.toUpperCase());
      };
    },
    handleSelect(item) {
      this.dataValue = item.label; // 回调在文框中显示的值
      this.$emit('input', item.value);// 绑定到父组件的值
    },
  }
};
</script>

父页面上引用它

<SearchLawfirmName v-model="searchLawfirmName" :allInfos="allData"></SearchLawfirmName>
import SearchLawfirmName from "@/components/SearchLawfirmName/index.vue";
export default {
data() {
    return {
      allData:[
        { value: 'result1', label: 'Result 1' },
        { value: 'result2', label: 'Result 2' },
        { value: 'result3', label: 'Result 3' }
      ],
      searchLawfirmName:null
     }
   }   
}

上面代码中,我们通过import引入了自定义组件,再将组件选中的当前值赋给页面属性searchLawfirmName,我们将异步的数据列表allData通过allInfos参数进行传递。