思路: 1. 一进入到页面,就获取缓存当中的数据; 2. 当点击input搜索框时,拿到input双向数据绑定的值; 3. 判断缓存中有没有值,没有就存当前的值; 4. 如果缓存当中有值,判断是不是重复值,是就删除当前值,并重新缓存到数组头部,不是就缓存到数组头部; 5. 判断数组长度若是大于5,就删除数组尾部的值.
<uni-nav-bar fixed="true" style="display: flex;justify-content: center; margin-top: 15px;" :status-bar="true" :border="false" class="NavBar" :rightText="searchtext" left-icon="back" @clickLeft="goBack()"> <view class="top_flex"> <view class="user_top_seach"> <u-icon size="50" name="search" color="#999" @click="searchAll" @keyup.enter="searchAll"></u-icon> <input class="inputtext" type="text" v-model="inputTxt" placeholder="请输入" /> <view class="close_box" @click="clearinputTxt"> <u-icon size="10" name="close" color="#ffffff"></u-icon> </view> </view> <view class="oncloer_bnt"> 取消 </view> </view> </uni-nav-bar> <view class="searhcHistory"> <view class="th"> <text>搜索历史</text> <text class="txt" @click="clearAll">清空历史</text> </view> <view class="td"> <text v-for="(item,index) in stoageHistory" :key="index" @click="hotClick(item)">{{item}}</text> </view> </view> <template/> <script> import uniNavBar from '@/component/uni-nav-bar/uni-nav-bar.vue' export default { data() { return { stoageHistory: ['语文','数学','体育','历史','音乐','生物安徽'], searhcHistorySecond: ['服饰','运动','鞋包','配饰','生鲜','母婴','数码','美妆'], inputTxt: '' } }, created:function(){ //获取localstorage let storage=window.localStorage; if(storage.getItem('searchWord') !== null){ this.stoageHistory = JSON.parse(storage.getItem('searchWord')); } }, methods: { searchAll:function(){ let val = this.inputTxt.trim(); if(val != ''){ let storage = window.localStorage; if(storage.getItem('searchWord') == null){ this.stoageHistory.unshift(val); storage.setItem('searchWord',JSON.stringify(this.stoageHistory)); }else{ if(this.stoageHistory.indexOf(val) != -1){ this.stoageHistory.splice(this.stoageHistory.indexOf(val), 1); this.stoageHistory.unshift(val); }else{ this.stoageHistory.unshift(val); } if(this.stoageHistory.length > 5){ this.stoageHistory.pop(); } storage.setItem('searchWord',JSON.stringify(this.stoageHistory)); } } this.inputTxt = ''; }, clearAll() { this.stoageHistory = []; }, hotClick(item) { this.inputTxt = item; }, clearinputTxt() { this.inputTxt = ''; } } } </script>