搜索后保存搜索历史,点击搜索历史再去搜索
<!-- searchBox. -->
<div class="search_row">
<div class="search-box">
<i class='iconfont icon-sousuo'></i>
<input type="text"
v-model="inputMsg"
ref='input' class='box'
:placeholder='placeholder'>
<i @click='clearMsg' v-show='inputMsg' class='iconfont icon-quxiao'></i>
</div>
<button @click="searchAll()">搜索</button>
</div>
<!-- 历史记录 -->
<div class="search_history">
<div class="top">
<h3>历史记录</h3>
<i class="iconfont icon-delete" @click="deleteHistory"></i>
</div>
<ul class="search_list" >
<li v-for="(item,index) in historyList" :key="index" @click="hotSearch(item)">{{item}}
</li>
</ul>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
inputMsg:'',
placeholder:'搜索关键词...',
shopList:[1],//店铺列表
commodityList:[],//商品列表
historyList:[]//搜索历史列表
},
created:function(){
var that = this;
//获取localstorage
let storage=window.localStorage;
if(storage.getItem('searchWord') !== null){
that.historyList = JSON.parse(storage.getItem('searchWord'));
}
// that.historyWord = JSON.parse(localStorage.getItem("searchWord")||'[]');
// that.historyList=localStorage.getItem('historyList'||'[]');
// that.historyList = that.historyWord.split(','); //将字符串转成数组
// that.historyList = that.historyWord;
console.log(that.historyList,'that.historyList')
},
methods: {
clearMsg(){
vm.inputMsg = '';
},
//清除历史记录
deleteHistory(){
vm.historyList.splice(0);
localStorage.clear();
console.log(vm.historyList,'deleteHistory');
},
//搜索
searchAll:function(){
console.log('sousosu');
var that = vm;
var val = that.inputMsg.trim();
if(val != ''){
let storage = window.localStorage;
if(storage.getItem('searchWord') == null){
that.historyList.unshift(val);
storage.setItem('searchWord',JSON.stringify(that.historyList));
}else{
console.log(that.historyList,'historyList');
if(that.historyList.indexOf(val) != -1){
that.historyList.splice(that.historyList.indexOf(val), 1);
that.historyList.unshift(val);
}else{
that.historyList.unshift(val);
}
if(that.historyList.length > 5){
that.historyList.pop();
}
storage.setItem('searchWord',JSON.stringify(that.historyList));
}
}
//2
// if (that.historyList.length > 0) { // 有数据的话 判断
// if (that.historyList.indexOf(val) !== -1) { // 有相同的,先删除 再添加
// that.historyList.splice(that.historyList.indexOf(val), 1)
// that.historyList.unshift(val)
// } else { // 没有相同的 添加
// that.historyList.unshift(val)
// }
// } else { // 没有数据 添加
// that.historyList.unshift(val)
// }
// if (that.historyList.length > 6) { // 保留六个值
// that.historyList.pop()
// }
// localStorage.setItem('searchWord', JSON.stringify(that.historyList));
//3
},
hotSearch:function(item){
vm.inputMsg=item;
vm.searchAll();
},
},
});
</script>