前端vue2框架中搜索框的历史记录实现代码
时间: 2024-05-01 17:24:05 浏览: 14
在Vue2框架中,实现搜索框的历史记录可以使用localStorage存储搜索记录,并在页面中展示出来。
下面是一个简单的实现代码:
```html
<!-- 搜索框 -->
<input type="text" v-model="keyword" @keyup.enter="search" />
<!-- 历史记录 -->
<div v-if="history.length > 0">
<h3>搜索历史</h3>
<ul>
<li v-for="(item, index) in history" :key="index" @click="selectHistory(item)">
{{ item }}
</li>
</ul>
</div>
```
```javascript
export default {
data() {
return {
keyword: '',
history: []
}
},
mounted() {
// 从localStorage中读取历史记录
this.history = JSON.parse(localStorage.getItem('searchHistory')) || []
},
methods: {
search() {
// 搜索处理
// ...
// 存储搜索记录到localStorage中
if (this.keyword.trim() !== '') {
this.history.unshift(this.keyword)
localStorage.setItem('searchHistory', JSON.stringify(this.history))
}
},
selectHistory(item) {
// 点击历史记录处理
this.keyword = item
this.search()
}
}
}
```
以上代码中,使用了v-model指令将搜索框的值与Vue实例的`keyword`属性进行绑定,使用了`@keyup.enter`事件监听回车键,触发`search`方法进行搜索处理。在搜索处理中,将搜索关键字存储到历史记录中,并使用`localStorage`进行本地存储。在页面中展示历史记录时,使用`v-for`指令遍历历史记录数组,使用`@click`事件监听点击事件,触发`selectHistory`方法进行搜索处理。
需要注意的是,以上代码只是一个简单的实现示例,实际应用中还需要进行一些优化,比如设置历史记录的最大数量、去重等。