美文网首页
vue 历史搜索记录读取新增删除

vue 历史搜索记录读取新增删除

作者: 中國式情調 | 来源:发表于2019-11-11 21:22 被阅读0次
    1 案例说明

    ​ 实现搜索历史展示、搜索内容跳转、搜索历史清空,限制搜索历史展示数目,历史记录存储于本地 localStorage

    2 案例演示
    search.gif
    2 源码

    ​ 本项目 github 源码:https://github.com/trp1119/vue-small-case

    <template>
      <div id="app">
        <div class="search-area">
          <div class="search">
            <input v-model="input" type="text" placeholder="请输入搜索内容">
          <button @click="handleSearchResult(input)">搜索</button>
          </div>
          <div class="content">
            <span>搜索历史</span>
            <span class="cancel" @click="clearHistory">清空</span>
          </div>
          <div class="history">
            <span class="norecord" v-if="historyList.length == 0">暂时搜索记录</span>
            <span
              class="record"
              v-else
              v-for="(historyItem, index) in historyList"
              :key="index"
              @click="handleSearchResult(historyItem)"
            >
              {{historyItem}}
            </span>
          </div>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: 'app',
      data () {
        return {
          input: '',
          historyList: []
        }
      },
      mounted () {
        if (localStorage.getItem('localHistory') !== null) {
          this.historyList = localStorage.getItem('localHistory').split('|')
        }
      },
      methods: {
        /**
         * 执行搜索
         */
        handleSearchResult (val) {
          if (val === '') {
            alert('请输入搜索内容!')
            return
          }
          this.setlocalHistory(val) // 将搜索值加入本地localStorage
          this.historyList = localStorage.getItem('localHistory').split('|') // 从本地localStorage取出搜索历史并展示
          this.input = '' // 清空输入框
          // alert(`跳转至 ${val} 搜索结果页`) // 跳转至搜索结果页
        },
        /**
         * 加入历史搜索记录
         */
        setlocalHistory (val) {
          val = val.trim()
          let localHistory = localStorage.getItem('localHistory')
          if (localHistory === null) {
            localStorage.setItem('localHistory', val) // 若未设置过则直接设置本地存储
          }else {
            let localHistoryArray = localHistory.split('|').filter(item => item != val) // 删除搜索历史中与本次输出重复项
            if (localHistoryArray.length > 0) {
              localHistory = val + '|' + localHistoryArray.join('|') // 新增记录
            }
            if (localHistory.split('|').length > 10) { // 最大历史搜索记录10条
              localHistoryArray = localHistory.split('|')
              localHistoryArray.pop() // 删除最旧一项
              localHistory = localHistoryArray.join('|')
            }
            localStorage.setItem('localHistory', localHistory) // 存入本地
          }
        },
        /**
         * 清空历史搜索记录
         */
        clearHistory () {
          localStorage.removeItem('localHistory') // 清空搜索历史
          this.historyList = []
        }
      }
    }
    </script>
    
    <style>
    #app {
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      /* text-align: center; */
      color: #2c3e50;
      margin-top: 60px;
    }
    .search-area {
      width: 230px;
      height: 120px;
      border: 1px solid #ccc;
      padding: 20px;
    }
    .content {
      width: 225px;
      font-size: 12px;
      margin-top: 10px;
    }
    .content .cancel {
      float: right;
      color: #1F8CEB;
      cursor: pointer;
    }
    .search button {
      margin-left: 10px;
    }
    .history {
      margin-top: 10px;
    }
    .history .norecord {
      font-size: 12px;
      color: #aaa;
      margin-left: 80px;
    }
    .history .record {
      display: inline-block;
      padding: 3px 10px;
      border-radius: 5px;
      background-color: #f6f6f6;
      font-size: 12px;
      color: #333;
      margin-right: 10px;
      margin-top: 5px;
      cursor: pointer;
    }
    </style>
    
    3 使用API
    3.1 localStorage API
    3.1.1 setItem 保存数据
    localStorage.setItem("key", "value");
    
    3.1.2 getItem 读取数据
    let localHistory = localStorage.getItem("key");
    
    3.1.3 removeItem 删除数据:
    localStorage.removeItem("key");
    
    3.2 String API
    3.2.1 String.prototype.split()

    split() 方法使用指定的分隔符字符串将一个 String 对象分割成子字符串数组。

    let str = "衣服|鞋子|裤子"
    let arr = str.split("|")
    console.log(arr) // ["衣服","鞋子","裤子"]
    
    3.3 Array API
    3.3.1 Array.prototype.filter()

    filter() 方法创建一个新数组,其包含通过所提供函数实现的测试的所有元素。

    filter 不会改变原数组,它返回通过 filter()callback 过滤后的新数组。如果没有任何数组元素通过测试,则返回空数组。

    // 参数 index 为当前处理项,index 为当前处理项的索引, arr 为当前处理数组
    let str = "裤子"
    let array = ["衣服","鞋子","裤子"]
    let newArr = array.filter((item, index, arr) => {
        item !== str // 返回数组中 >3 的值组成的新数组
    })
    console.log(newArr) // ["衣服","鞋子"]
    
    3.3.2 Array.prototype.join()

    join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。

    返回值为一个所有数组元素连接的字符串。如果 arr.length0,则返回空字符串。

    如果一个元素为 undefinednull,它会被转换为空字符串。

    let array = ["衣服","鞋子","裤子"]
    let str = array.join('|') // 使用 | 分隔数组中的每个元素,若缺省则用“,”分隔,若是空字符串''则没有分隔符
    console.log(str) // "衣服|鞋子|裤子"
    
    3.3.3 Array.prototype.pop()

    pop()方法从数组中删除最后一个元素,并返回所删除元素的值,并改变原数组。当数组为空时返回 undefined

    let array = ["衣服","鞋子","裤子"]
    let str = array.pop()
    console.log(str) // 裤子
    console.log(array) // ["衣服","鞋子"]
    

    相关文章

      网友评论

          本文标题:vue 历史搜索记录读取新增删除

          本文链接:https://www.haomeiwen.com/subject/dnoabctx.html