vue 模糊搜索

类似于elementUI 的 el-autocomplete远程搜索

参考:https://github.com/Daotin/fe-notes/issues/170

 1 <template>
 2   <div id="app">
 3     <!-- <input type="text" :value="filterText" @input="onInput" /> -->
 4     <input type="text" v-model="filterText" @input="onInput" @focus="focus()"  />
 5     <ul v-show="showList">
 6       <li v-for="item in filteredList" :key="item" @click="getText($event)">
 7         {{ item }}
 8       </li>
 9     </ul>
10   </div>
11 </template>
12 
13 <script>
14 export default {
15   name: "app",
16   data() {
17     return {
18       filterText: "",
19       list: [
20         "爱与希望",
21         "花海",
22         "Mojito",
23         "最长的电影",
24         "爷爷泡的茶"
25       ],
26       showList:false
27     };
28   },
29   computed: {
30     filteredList() {
31       if (!this.filterText) {
32         return this.list;
33       }
34       return this.list.filter(item => item.indexOf(this.filterText) > -1);
35     },
36     
37   },
38   methods: {
39     onInput(e) {
40       // console.log(e)
41       this.filterText = e.target.value;
42     },
43     focus(){
44       this.showList=true
45     },
46     // blur(){
47     //   this.showList=false
48     // },
49     getText(event){
50       console.log(event.target.innerText)
51       this.filterText = event.target.innerText
52       // window.body.click()
53     }
54   }
55 };
56 </script>

 另外考虑性能问题,可食用防抖和节流函数优化。

参考:https://www.jb51.net/article/185347.htm

/**
 * 函数防抖
 */
export function debounce(fn, delay) {
 // 记录上一次的延时器
 var timer = null;
 var delay = delay || 200;
 return function() {
  var args = arguments;
  var that = this;
  // 清除上一次延时器
  clearTimeout(timer)
  timer = setTimeout(function() {
    fn.apply(that,args)
  }, delay);
 }
}

 也可以使用第三方js库 fuse.js

参考:https://www.jianshu.com/p/44e8edb4c404

posted @ 2020-07-31 23:14  伟笑  阅读(260)  评论(0编辑  收藏  举报