vue 移动端搜索功能(带历史搜索记录)

£神魔★判官ぃ 2022-10-07 06:48 17阅读 0赞

实现效果如图:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2h1aHVodWph_size_16_color_FFFFFF_t_70

实现的功能:
1.点击搜索,把搜索的值存入本地记录,并展示
2.搜索相同的值,要删除旧数据,把新数据放进数组首位
3.清空历史记录

html代码:

  1. <div class="searchinp">
  2. <span @click="back" class="totrain"></span>
  3. <div class="input_box">
  4. <img class="btn_img" src="../assets/search.png" alt="" />
  5. <input type="text" v-model="search_val"/>
  6. </div>
  7. <button @click="get_search">搜索</button>
  8. </div>
  9. <div class="history">
  10. <p class="note">
  11. <span>历史搜索</span>
  12. <button @click="empty">
  13. <van-icon class="icon" name="delete-o" />
  14. <span>清除记录</span>
  15. </button>
  16. </p>
  17. <ul v-if="historyList.length>0">
  18. <li
  19. v-for="(item, index) in historyList"
  20. :key="index"
  21. @click="goSearchDetail(item)"
  22. >
  23. {
  24. { item }}
  25. </li>
  26. </ul>
  27. <p v-else style="text-align:center;margin:0 auto;font-size:16px;margin-top:20px">
  28. 暂无搜索记录
  29. </p>
  30. </div>

事件部分:

  1. <script>
  2. export default {
  3. name: "Search",
  4. data() {
  5. return {
  6. search_val: "", //搜索的内容
  7. historyList: [], //历史搜索记录,存本地
  8. };
  9. },
  10. mounted() {
  11. //如果本地存储的数据historyList有值,直接赋值给data中的historyList
  12. if (JSON.parse(localStorage.getItem("historyList"))) {
  13. this.historyList = JSON.parse(localStorage.getItem("historyList"));
  14. }
  15. },
  16. methods: {
  17. // 搜索
  18. get_search() {
  19. if (this.search_val == "") {
  20. // this.$toast("请输入搜索内容");
  21. this.$notify({ type: "primary", message: "请输入搜索内容" });
  22. return false;
  23. } else {
  24. // 没有搜索记录,把搜索值push进数组首位,存入本地
  25. if (!this.historyList.includes(this.search_val)) {
  26. this.historyList.unshift(this.search_val);
  27. localStorage.setItem("historyList", JSON.stringify(this.historyList));
  28. } else {
  29. //有搜索记录,删除之前的旧记录,将新搜索值重新push到数组首位
  30. let i = this.historyList.indexOf(this.search_val);
  31. this.historyList.splice(i, 1);
  32. this.historyList.unshift(this.search_val);
  33. localStorage.setItem("historyList", JSON.stringify(this.historyList));
  34. }
  35. //跳转到搜索结果页
  36. this.$router.push({
  37. path: "/home", //home是列表页
  38. query: {
  39. keyword: this.search_val,
  40. },
  41. });
  42. }
  43. },
  44. //点击历史搜索,跳转搜索结果页
  45. goSearchDetail(title) {
  46. this.$router.push({
  47. path: "/home",
  48. query: {
  49. keyword:title,
  50. // search_val: title,
  51. },
  52. });
  53. },
  54. //清空历史搜索记录
  55. empty() {
  56. this.$notify({ type: "success", message: "清空历史搜索成功" });
  57. localStorage.removeItem("historyList");
  58. this.historyList = [];
  59. },
  60. },
  61. };
  62. </script>

发表评论

表情:
评论列表 (有 0 条评论,17人围观)

还没有评论,来说两句吧...

相关阅读