searchHistory

本文介绍了一个JavaScript函数,用于管理本地存储的搜索历史记录。该函数能够添加新的搜索关键字,同时确保关键字不重复,并限制历史记录数量不超过八个。通过使用localStorage和JSON操作,实现了高效的历史记录管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function setHistory (keyword) {    
    let list = localStorage.getItem('historySearch')
    if(list){
      list = JSON.parse(list)
      let index = list.indexOf(keyword)
      if(index!=-1){ // 去重
        list.splice(index, 1)
      }
      list.unshift(keyword)
      if(list.length > 8){ // 最多8条历史记录
        list.splice(list.length-1)
      }
      localStorage.setItem('historySearch',JSON.stringify(list))
    }else{
      localStorage.setItem('historySearch',JSON.stringify([keyword]))
    }
}复制代码


转载于:https://juejin.im/post/5cf241cae51d4556da53d05b

// stores/searchStore.js import { defineStore } from 'pinia' export const useSearchStore = defineStore('search', { state: () => ({ searchHistory: [], }), actions: { addSearchHistory(query) { // 去重并限制最多保存10条记录 this.searchHistory = [ query, ...this.searchHistory.filter(item => item !== query) ].slice(0, 10) } } }) <!-- components/SearchComponent.vue --> <template> <div class="search-container"> <el-input v-model="searchQuery" placeholder="请输入搜索内容" @keyup.enter="handleSearch" clearable > <template #append> <el-button icon="Search" @click="handleSearch" :loading="isSearching" /> </template> </el-input> <div class="history-tags" v-if="searchStore.searchHistory.length"> <span class="history-label">搜索历史:</span> <el-tag v-for="(item, index) in searchStore.searchHistory" :key="index" class="history-tag" type="info" effect="plain" @click="selectHistory(item)" > {{ item }} </el-tag> </div> </div> </template> <script setup> import { ref } from 'vue' import { ElInput, ElButton, ElTag } from 'element-plus' import { useSearchStore } from '@/stores/searchStore' const searchStore = useSearchStore() const searchQuery = ref('') const isSearching = ref(false) let timeoutId = null // 防抖处理(300ms) const debounceSearch = (fn, delay = 300) => { return (...args) => { clearTimeout(timeoutId) timeoutId = setTimeout(() => { fn.apply(this, args) }, delay) } } // 实际搜索方法 const performSearch = async () => { if (!searchQuery.value.trim()) return try { isSearching.value = true // 这里替换实际的搜索接口调用 console.log('正在搜索:', searchQuery.value) await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟异步请求 searchStore.addSearchHistory(searchQuery.value.trim()) } finally { isSearching.value = false } } // 防抖后的搜索方法 const handleSearch = debounceSearch(() => { performSearch() }) // 选择历史记录 const selectHistory = (item) => { searchQuery.value = item performSearch() } </script> <style scoped> .search-container { max-width: 600px; margin: 20px auto; } .history-tags { margin-top: 15px; display: flex; flex-wrap: wrap; gap: 8px; } .history-tag { cursor: pointer; transition: all 0.3s; } .history-tag:hover { transform: scale(1.05); } .history-label { color: #666; font-size: 14px; margin-right: 8px; } </style>修改上述代码使得搜索历史记录持久化到本地存储
最新发布
05-15
<template> <view> <text class="text-title">翻译历史:</text> <uni-list v-for="(elem,index) in searchHistory" :key="index"> <uni-list-item :title="elem.searchValue" :rightText="getLanguageTransfer(elem.fromLanguage,elem.toLanguage)" @click="itemClick(elem)" clickable></uni-list-item> </uni-list> </view> </template> <script> import { sha256 } from 'js-sha256'; export default { data() { return { searchHistory: [], array: [{ name: '中文', code: 'zh-CHS' }, { name: '英文', code: 'en' }, { name: '德文', code: 'de' }, { name: '日文', code: 'ja' }, { name: '法文', code: 'fr' }, { name: '韩文', code: 'ko' }] } }, methods: { itemClick(data) { if (data.searchValue.length > 0) { console.log(data.searchValue); console.log(data.fromLanguage); console.log(data.toLanguage); let salt = (new Date).getTime(); let appKey = '03949e1a6a334f86'; let appSecret = '9u6wiw517BYJ8ggnFIdcwoYGmqtsOHUl'; let curtime = Math.round(new Date().getTime() / 1000); let input = data.searchValue.length <= 20 ? data.searchValue : data.searchValue.slice(0, 10) + data .searchValue.length + data.searchValue.slice(-10); uni.request({ url: '/youdaoApi/api', url: 'https://openapi.youdao.com/api', method: 'GET', data: { q: data.searchValue, from: data.fromLanguage, to: data.toLanguage, appKey: appKey, salt: salt, curtime: curtime, sign: sha256(appKey + input + salt + curtime + appSecret), signType: 'v3' }, success: (data) => { this.$store.commit('setOutcome', data); uni.switchTab({ url: '/pages/translateresult/translateresult' }); } }) } }, getLanguageTransfer(from, to) { let fromStr = this.array.find(item => { return item.code == from; }); let toStr = this.array.find(item => { return item.code == to; }); return fromStr.name + '->' + toStr.name; } }, onshow() { this.searchHistory = Array.from(this.$store.getters.getHistoryList); console.log(this.searchHistory); console.log("1" + this.$store.getters.getHistoryList); this.serachHistory.reverse(); } } </script> <style> .text-title { font-size: 45rpx; color: coral; margin-top: 100rpx; } </style>
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值