RecipeSearchViewModel.ets 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { IBestToast, userInfo, UserInfo, YTAvoid, yTRouter } from "basic"
  2. import { AppStorageV2, PersistenceV2 } from "@kit.ArkUI"
  3. import { RecipSearch } from "../model/Persistence"
  4. import { Cuisine, Recipe } from "../model/Index"
  5. import { BabyFoodApi } from "../Apis/BabyFoodApi"
  6. import { DiaLogPageEnum, DiaLogParam, YTDiaLogModel } from "basic/src/main/ets/models/YTDiaLogModel"
  7. @ObservedV2
  8. export class RecipeSearchViewModel{
  9. @Trace safeTop: number = 0
  10. @Trace delModel: boolean = false
  11. @Trace keyWord: string = ''
  12. @Trace searchList: Recipe[] = []
  13. // 用户信息
  14. @Trace userInfo: UserInfo = AppStorageV2.connect<UserInfo>(UserInfo, 'UserInfo', () => userInfo)!
  15. @Trace historicalSearchRecords: RecipSearch = PersistenceV2.connect(RecipSearch, `${this.userInfo.getId()}Tags`, () => new RecipSearch())!
  16. linearInfo: LinearGradientOptions = {
  17. colors: [ ['#B9FD2A', 0.01], ['#F5FD6D', 1] ],
  18. angle: 150
  19. }
  20. constructor() {
  21. this.safeTop = AppStorage.get(YTAvoid.SAFE_TOP_KEY) as number;
  22. }
  23. // 点击开始搜索
  24. async onSearch(){
  25. if(!this.keyWord) {
  26. IBestToast.show('请输入搜索内容')
  27. return
  28. }
  29. const targetIndex: number = this.historicalSearchRecords.searchList.indexOf(this.keyWord)
  30. if(targetIndex !== -1){
  31. this.historicalSearchRecords.searchList.splice(targetIndex, 1)
  32. }
  33. this.historicalSearchRecords.searchList.unshift(this.keyWord)
  34. this.searchList = await BabyFoodApi.getAllRecipes(this.keyWord)
  35. if(this.searchList.length === 0) {
  36. IBestToast.show('没有搜索结果')
  37. }
  38. }
  39. // 删除搜索记录
  40. onDelSearch(index: number){
  41. this.historicalSearchRecords.searchList.splice(index, 1)
  42. }
  43. // 清空搜索框
  44. clearKeyWord(){
  45. this.keyWord = ''
  46. this.searchList = []
  47. }
  48. }