效果图
html代码
<div class="search">
<div class="search-btn">
<el-input
v-model.trim="searchContent"
size="small"
style="width: 193px"
class="mr10"
placeholder="请输入搜索内容"
@focus="showHistory"
@blur="hiddenHistory"
>
</el-input>
<el-button type="primary" size="small" @click="search">搜索</el-button>
</div>
<div :class="[isHistoryShow ? 'search-history' : 'show']">
<div class="search-history-header">
<span class="search-history-header__title">搜索记录</span>
<span
v-if="historyShowList&&historyShowList.length > 0"
class="search-history-header__icon"
@click="clearHistory"
>
<i class="el-icon-delete"></i></span>
</div>
<div
v-if="historyShowList&&historyShowList.length > 0"
class="search-history-content">
<ul>
<li
v-for="item in historyShowList"
:key="item"
@click="historySearch(item)">{{ item }}</li>
</ul>
</div>
<div v-else class="search-history-none">
暂无数据
</div>
</div>
</div>
2.js部分代码
data() {
return {
activeName: 'table',
isHistoryShow: false,
historyList: [],
historyShowList: [],
localList: {
'table': 'dataMapTableHistory',
'topic': 'dataMapTopicHistory',
'api': 'dataMapApiHistory'
}
}
},
methods: {
selectProject() {
this.$refs['table'][0].refresh()
},
search() {
if (this.removeDedup(JSON.parse(localStorage.getItem(this.localList[this.activeName])))) {
this.historyList.push(this.searchContent)
localStorage.setItem(this.localList[this.activeName], JSON.stringify(this.historyList))
}
this.selectProject()
},
removeDedup(removeList) {
let isSave = true
removeList?.forEach(item => {
if (this.searchContent === item) isSave = false
})
return isSave
},
historySearch(val) {
this.searchContent = val
this.selectProject()
},
showHistory() {
this.historyShowList = JSON.parse(localStorage.getItem(this.localList[this.activeName]))
this.isHistoryShow = true
},
clearHistory() {
localStorage.removeItem(this.localList[this.activeName])
},
hiddenHistory() {
setTimeout(() => {
this.isHistoryShow = false
}, 300)
},
}
对于触发失去焦点事件,点击历史记录失效,采用的是setTimeout(() => {},300),延迟300ms,就可以触发点击事件了
1.先保存数据到本地,我这里使用的是localstorage。2.保存数据要去重,防止重复保存,这里使用JSON.stringfy保存数据是将数据JSON化,防止保存数据变为字符串
search() {
const val = JSON.parse(localStorage.getItem(this.localList[this.activeName]))
if (this.removeDedup(val)) {
this.historyList.push(this.searchContent)
localStorage.setItem(this.localList[this.activeName],
JSON.stringify(this.historyList))
}
this.selectProject()
},
removeDedup(removeList) {
let isSave = true
removeList?.forEach(item => {
if (this.searchContent === item) isSave = false
})
return isSave
},
3.触发focus(输入框获取焦点)事件,和blur(输入框失去焦点事件)
showHistory() {
this.historyShowList =
JSON.parse(localStorage.getItem(this.localList[this.activeName]))
this.isHistoryShow = true
},
hiddenHistory() {
setTimeout(() => {
this.isHistoryShow = false
}, 300)
},