Vue防抖(debounce)微项目

一、防抖概念

一定时间段(结束)触发最后次——间隔触发,在执行时间段内被再次触发,则重新计数(清除上一次定时器),类似游戏回城中断,再次回城重新计数,eg:

    //初始化定时器
    timer: null

    //定时器调用函数
    this.timer = setTimeout(() => {
        this.showLists(this.keyword);
    }, 500);

    //所被调用函数,清除timer,为下次调用做准备
    showLists(keyword) {
        clearTimeout(this.timer)
    }

二、防抖微项目

项目要求: 

仿TaoBao搜索框,输入内容(keyword)搜索框下方显示模糊查询结果,所有显示内容均可跳转,eg:

项目简述:

  1. 结果显示框是否显示,V-if(通过length进行判断)

  1. 双结果选择(判断)显示,watch监视

  1. 获取输入值,@keyup.native

  1. 遍历由computed返回列表数据,利用<a>标签跳转,v-for

  1. 防抖函数定时器设置,jsonp数据传递函数调用,debounceSearch

  1. keyword传递数据与获取,赋值已定义数组,this.$jsonp

项目代码块:

data模块:

   data() {
    return {
      keyword: "",
      suggestionList: {},
      cacheList: {}, //cache the data
      isShow: false,
      timer: null, //timer closed loop
    };
  },

methods模块:

   methods: {
    showLists(keyword) {
      clearTimeout(this.timer)
      if (this.cacheList[keyword]) {
        return this.cacheList[keyword];
      } else {
        this.$jsonp("https://suggest.taobao.com/sug", {
          q: keyword,
        }).then((res) => {
          this.suggestionList = res.result;
          // console.log(res);
          // console.log(typeof(res.result));
          this.cacheList[keyword] = res.result;         
        });
      }
    },

    // Anti-shaking function
    debounceSearch() {
      this.timer = setTimeout(() => {
        this.showLists(this.keyword);
      }, 500);
    },

    // need the other link
    search() {
      this.showLists(this.keyword);
    },

    showSuggestionList() {
      this.debounceSearch();
    },
  },

项目逻辑图:

小白博主一枚,如代码有不足之处,望各位指正(希望生活更加精彩,爱生活~)

节流概念链接:https://blog.csdn.net/Chris__Feng/article/details/128857037

防抖微项目链接:https://github.com/ChrisF1109/Vue-debounce-throttling-.git,位于master分支中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值