HarmonyOS
封装搜索历史工具

目标:基于首选项封装搜索历史存储工具
import { preferences } from '@kit.ArkData'
class History {
store?: preferences.Preferences
getStore(){
if(!this.store){
const ctx = AppStorage.get<Context>('context')
this.store = preferences.getPreferencesSync(ctx, {name: 'history-store'})
}
return this.store
}
/**
* 存储搜索
*/
async setItem(keyword: string){
this.getStore().putSync(keyword, keyword)
await this.getStore().flush()
}
/**
* 删除一个
*/
async delItem(keyword: string){
this.getStore().deleteSync(keyword)
await this.getStore().flush()
}
/**
* 删除所有
*/
async clear(){
this.getStore().clearSync()
await this.getStore().flush()
}
/**
* 取出搜索
*/
getAll(){
// {ts: 'ts', js: 'js', vue: 'vue'}
// Object.keys() 取出所有的键 Object.values() 取出所有的值
const obj = this.getStore().getAllSync()
return Object.keys(obj)
}
}
export const history = new History()
34.子传父(用函数传)
//子组件
onSearch: (val: string) => void = () => { }
.onClick(() => {
this.onSearch(keyword)
})
//父组件接收
SearchHistory({
onSearch: keyword => {
this.keyword = keyword
}
})
2万+

被折叠的 条评论
为什么被折叠?



