Vue移动端搜索页面的历史记录写法

Vue移动端搜索页面的历史记录写法

前言

本文用于记录对于搜索页的历史记录的学习。

预览

先上两张图,分别为展示隐藏搜索列表和历史记录。

image
image

html部分




JS部分


    methods: {

      // 聚焦

      inputFocus () {

        this.getHistorys()

        this.showHistory = true

      },

      // historys存入localStorage

      setHistorys () {

        // 搜索框有内容且不在历史记录里

        let vm = this

        if (vm.searchValue && vm.searchValue !== '' && vm.searchValue !== ' ' && vm.history.indexOf(vm.searchValue) === -1) {

          let Arr = Array.from(new Set(vm.history))

          vm.history = [vm.searchValue, ...Arr]

        }

        // 历史记录只保存6条

        if (vm.history && vm.history.length && vm.history.length > 6) {

          vm.history = vm.history.slice(0, 6)

        }
        localStorage.setItem('historys', JSON.stringify(vm.history))

      },

      // historys获取localStorage

      getHistorys () {

        let history = localStorage.getItem('historys')

        if (history) {

          this.history = JSON.parse(history)

        }

      },

      // 失去焦点

      inputBlur () {

        this.setHistorys()
 this.orderList = []

        this.page = 0

        this.getWorkerApi()

        this.showHistory = false

      },

      // 回车

      search () {

        // 失焦

        this.$refs.test.blur()
      },

      // 删除历史记录

      clearHistory () {

        this.history = []

        localStorage.removeItem('historys')

      },

    ...

    },

  • 首先inputFocus()方法聚焦即点击搜索区时,显示历史记录,并调用获取历史记录的方法getHistorys()。这里使用localStorage存历史记录,所以使用 localStorage.getItem('historys')拿到缓存中的历史记录给this.histor用于展示历史记录区。

  • inputBlur()失去搜索区焦点时隐藏历史记录区,并调用添加历史记录方法setHistorys(),接着初始化搜索添加并条用搜索方法显示展示区列表。这里搜索框有内容且不在历史记录里时才将搜索内容添加到历史记录展示区和通过localStorage.setItem()放入缓存中。添加上限是6条,超出的会从第一条覆盖。要注意放入缓存中的数据必须是JSON格式。

  • search()搜索区按回车时执行此方法。按回车时让其失焦搜索框,然后进入inputBlur()的方法中。

  • clearHistory ()清空历史记录方法,使用localStorage.removeItem('historys')并初始化历史记录显示区。

  • 其他的逻辑如选中历史记录和选中展示区列表数据等就不赘述了。

总结

历史记录功能主要是运用聚焦、失焦、回车、缓存等方法,对数据进行删选和拼接再展示。

你可能感兴趣的:(Vue移动端搜索页面的历史记录写法)