一、函数防抖

/ 函数防抖:只针对最后一次输入触发 /

  1. <body>
  2. <button id="btn">btn</button>
  3. <script>
  4. let timeout =null;
  5. function debounce(fn,wait){
  6. if(timeout){
  7. clearTimeout(timeout)
  8. }
  9. timeout = setTimeout(fn,wait);
  10. }
  11. var btn = document.getElementById("btn");
  12. var itemout=null
  13. btn.onclick = function(){
  14. debounce(function(){
  15. console.log(4)
  16. },1000)
  17. }
  18. </script>
  19. </body>

二、封装防抖函数util/debounce.js

  1. let timeout = null
  2. function debounce(fn, wait) {
  3. if(timeout !== null) clearTimeout(timeout)
  4. timeout = setTimeout(fn, wait)
  5. }
  6. export default debounce

三、watch方法中使用

  1. <script>
  2. import debounce from "@/utils/debounce";
  3. import axios from "axios-jsonp-pro";
  4. export default {
  5. name: "Search",
  6. data() {
  7. return {
  8. keyword: "",
  9. musics: ""
  10. };
  11. },
  12. watch: {
  13. keyword(newValue) {
  14. /* 函数防抖:只针对最后一次输入触发 */
  15. debounce(() => {
  16. var url = `https://douban.uieee.com/v2/music/search?q=${newValue}`;
  17. axios.jsonp(url).then(res => {
  18. this.musics = res.musics;
  19. });
  20. },1000);
  21. }
  22. }
  23. };
  24. </script>