vue+elementUI实现搜索框历史记录

1、jsp部分(参考elementUI官方):

        <el-autocomplete
          class="inline-input"
          v-model="listQuery.cnoOrName"
          :fetch-suggestions="querySearch"
          @keyup.enter.native="findFirPage"
          @select="findFirPage"
        ></el-autocomplete>

2、主要是利用浏览器本身自己带的localStorage存储空间,下面是实现的JSON


data(){
return{
noRoNameHistory: []  //定义一个存放历史搜索记录的数组
}
}
 findFirPage() {
      this.listQuery.page = 1    //自己项目定义的查询页面
      this.setIntoStorage()
      this.findPage()           //项目定义的查询方法
    },
      mounted() {              //组件加载后给noRoNameHistory 赋值
          this.noRoNameHistory = this.setIntoStorage()
      },
      querySearch(queryString, cb) {
          // 调用 callback 返回建议列表的数据
          const noRoNameHistory = JSON.parse(localStorage.getItem('coOrName'))
          const results = queryString ? noRoNameHistory.filter(this.createFilter(queryString)) : noRoNameHistory
          cb(results)
      },
      createFilter(queryString) {
          return (noRoNameHistory) => {
              return (noRoNameHistory.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
          }
      },
      setIntoStorage() {
          const noArr = []// 历史记录数组
          const value = this.listQuery.cnoOrName
          const cnoOrName = 'coOrName'
          noArr.push({ value: value, type: cnoOrName })
          console.log(this.listQuery.cnoOrName)
          if (JSON.parse(localStorage.getItem(cnoOrName))) {
              // 判断是否已有xxx查询记录的localStorage
              if (localStorage.getItem(cnoOrName).indexOf(value) > -1) { // 判断是否已有此条查询记录,若已存在,则不需再存储
                  return
              }
              if (JSON.parse(localStorage.getItem(cnoOrName)).length >= 5) {
                  const arr = JSON.parse(localStorage.getItem(cnoOrName))
                  arr.pop()
                  localStorage.setItem(cnoOrName, JSON.stringify(arr))
              }
              localStorage.setItem(cnoOrName, JSON.stringify(noArr.concat(JSON.parse(localStorage.getItem(cnoOrName)))))
          } else { // 首次创建
              localStorage.setItem(cnoOrName, JSON.stringify(noArr))
          }
          console.log(localStorage.getItem('coOrName'))
  },

你可能感兴趣的:(VUE前端)