美文网首页前端学习
项目经验 | Vue搜索框 + debounce防抖

项目经验 | Vue搜索框 + debounce防抖

作者: 格致匠心 | 来源:发表于2019-06-28 21:01 被阅读0次
    <el-input v-model="keywords"/>
    
    import { $public, $formTools } from '@/helper'
    export default {
      data() {
        return {
          keywords: ''
        }
      },
      watch: {
        keywords () {
          this.debouncedSearch()
        }
      },
      created () {
        this.debouncedSearch = $public._debounce(this.fetchPage)
      },
      methods: {
        fetchPage (page = 1) {
          let optionsObj = { limit: 10, offset: (page - 1) * 10 }
          if (this.keywords.length > 0) optionsObj['search'] = this.keywords
          let options = this.$formTools.getOptions('get', optionsObj)
          this.$apis.manageGetProblemList(options).then(res => {
            this.result = res.result
          })
        }
      }
    }
    

    小项目不想引入lodash,所以是手写的debounce和throttle

    export default {
      _debounce (fn, delay) {
        delay = delay || 600
        let timer
        return function () {
          let ctx = this
          let args = arguments
          if (timer) {
            clearTimeout(timer)
          }
          timer = setTimeout(() => {
            timer = null
            fn.apply(ctx, args)
          }, delay)
        }
      },
      _throttle (fn, interval) {
        let last
        let timer
        interval = interval || 600
        return function () {
          let ctx = this
          let args = arguments
          let now = new Date()
          if (last && now - last < interval) {
            clearTimeout(timer)
            timer = setTimeout(function () {
              last = now
              fn.apply(ctx, args)
            }, interval)
          } else {
            last = now
            fn.apply(ctx, args)
          }
        }
      }
    }
    

    相关文章

      网友评论

        本文标题:项目经验 | Vue搜索框 + debounce防抖

        本文链接:https://www.haomeiwen.com/subject/vlqycctx.html