欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

vue Element-ui input 远程搜索实例详解

程序员文章站 2022-05-24 12:37:49
...
本文分为html,js和css代码给大家详细介绍了vue Element-ui input 远程搜索与修改建议显示模版功能,感兴趣的朋友一起看看吧,希望能帮助到大家。

html:

<template>
 <el-autocomplete popper-class="my-autocomplete" custom-item="my-remote" v-model="state" :fetch-suggestions="querySearch" placeholder="默认空" icon="close" :on-icon-click="handleIconClick">
 </el-autocomplete>
</template>

js:

<script>
import Vue from 'vue'
Vue.component('my-remote', {
 functional: true,
 render: function(h, ctx) {
  var item = ctx.props.item;
  let str = h('li', ctx.data, [
   h('p', { attrs: { class: 'name' } }, [item.value]),
   h('span', { attrs: { class: 'addr' } }, [item.address])
  ]);
  if (item.str) { // 根据参数不同 修改原模版结构
   str = h('center', { attrs: { class: 'ems' } }, [item.str])
  }
  return str
 },
 props: {
  item: { type: Object, required: true }
 }
});
export default {
 data() {
  return {
   restaurants: [],
   state: '',
   timeout: null,
   _that: {} // 记录this,用来发起http请求
  };
 },
 methods: {
  querySearch(queryString, cb) {
   let restaurants = this.restaurants;
   if (restaurants.length > 0) { // 如果参数都没变化,则使用缓存数据,避免请求沉积
    let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
    cb(results);
   } else {
    const qtype = ‘参数';
    this._that.$http('/inner', { qtype: qtype })
     .then((res) => {
       restaurants = this.loadAll(res);
       this.restaurants = restaurants;
       let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
       cb(results);
     })
     .catch((err) => {
      restaurants = this.loadAll();
      let results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      cb(results);
     });
   }
  },
  createFilter(queryString) {
   return (restaurant) => {
    if (restaurant.str) return false;
    return (restaurant.value.indexOf(queryString.toLowerCase()) === 0);
   };
  },
  loadAll(data) {
   let serier = [];
   if (data) {
    for (let i = 0, l = data.length; i < l; i++) {
     let a = data[i];
     let b = '';
     if (typeof a === "object") {
      b = a[1];
      a = a[0];
     }
     serier.push({ "value": a, "address": b })
    }
   } else { // 如果没有请求到数据,则显示暂无数据!
    serier.push({ "str": '暂无数据' })
   }
   return serier;
  },
  handleIconClick(ev) {
   this.state = "";
  }
 },
 mounted() {
  this._that = this;
 }
}
</script> 

css:

<style lang="scss">
.my-autocomplete {
 li {
  line-height: normal !important;
  padding: 7px !important;
 
  .name {
   text-overflow: ellipsis;
   overflow: hidden;
  }
  .addr {
   font-size: 12px;
   color: #b4b4b4;
  }
 
  .highlighted .addr {
   color: #ddd;
  }
 }
 .ems {
  font-size: 12px;
  color: #b4b4b4;
 }
}
</style> 

相关推荐:

JavaScript之replace实现搜索关键字高亮显示方法

jquery select插件异步实时搜索实现方法

Bootrap和Vue实现仿百度搜索功能实例

以上就是vue Element-ui input 远程搜索实例详解的详细内容,更多请关注其它相关文章!