搜索框历史搜索记录vue
时间: 2025-01-24 18:10:50 AIGC 浏览: 54
在Vue.js中实现搜索框的历史搜索记录功能,可以通过以下步骤来完成:
1. **创建搜索框组件**:
首先,创建一个搜索框组件,包含一个输入框和一个显示历史搜索记录的列表。
2. **存储历史搜索记录**:
使用浏览器的`localStorage`或`sessionStorage`来存储历史搜索记录。这样即使用户刷新页面,历史记录也不会丢失。
3. **处理输入事件**:
当用户输入内容并提交时,将输入的内容添加到历史记录中,并更新存储。
4. **显示历史搜索记录**:
从存储中读取历史记录,并将其显示在搜索框下方。
以下是一个简单的示例代码:
```vue
<template>
<div>
<input v-model="searchQuery" @keyup.enter="addToHistory" placeholder="请输入搜索内容">
<button @click="addToHistory">搜索</button>
<ul>
<li v-for="(item, index) in searchHistory" :key="index" @click="selectHistory(item)">
{{ item }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: '',
searchHistory: []
};
},
created() {
this.loadHistory();
},
methods: {
addToHistory() {
if (this.searchQuery.trim() !== '') {
this.searchHistory.unshift(this.searchQuery.trim());
this.saveHistory();
this.searchQuery = '';
}
},
saveHistory() {
localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
},
loadHistory() {
const history = localStorage.getItem('searchHistory');
if (history) {
this.searchHistory = JSON.parse(history);
}
},
selectHistory(item) {
this.searchQuery = item;
}
}
};
</script>
<style scoped>
input {
width: 200px;
padding: 5px;
}
ul {
list-style-type: none;
padding: 0;
}
li {
cursor: pointer;
padding: 5px;
}
li:hover {
background-color: #f0f0f0;
}
</style>
```
这个示例代码展示了如何在Vue.js中实现一个简单的搜索框历史记录功能。用户输入内容并点击搜索按钮后,输入的内容会被添加到历史记录中,并存储在`localStorage`中。用户也可以点击历史记录项来快速选择搜索内容。
阅读全文
相关推荐




















