vue input 输入 防抖

<template>
   
  <input @keyup="aaa"
         v-model="val" />

  <ul>
    <li v-for="(item,index) in list"
        :key="index">{{item.q}}</li>
  </ul>

</template>

<script>
 
export default {
  
  data() {
    return {
      
      val: 'html',
      list: [],
      timer: '',
    }
  },
  mounted() {
 
  },
  methods: {
    aaa() {
      let _this = this

      clearTimeout(this.timer) //清楚定时器

      this.timer = setTimeout(() => {
        this.FetchJsonp( 
          `https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&wd=${this.val}`
        )
          .then(function (response) {
            return response.json()
          })
          .then(function (json) {
            console.log('parsed json', json.g)
            _this.list = json.g
          })
          .catch(function (ex) {
            console.log('parsing failed', ex)
          })
      }, 1000)
    },
  },
  updated() {},
}
</script>

<style scoped lang="less">
</style>
Vue 3中的防抖(debounce)技术是一种常用的功能,用于控制函数的执行频率。它主要应用在输入框(input)场景中,目的是为了提高性能和用户体验。在用户进行输入时,如果立即响应每次键盘事件来处理逻辑,会导致大量的计算和资源消耗,尤其在处理复杂或数据密集型逻辑时更为明显。防抖技术可以确保在用户停止输入一段时间后,才执行相关的处理函数。 在Vue 3中,可以通过组合式 API(Composition API)来实现防抖功能。你可以使用 `ref`, `computed`, `watch` 或 `watchEffect` 等组合式 API 来创建一个防抖函数。以下是一个简单的防抖函数示例: ```javascript import { ref, onMounted, onUnmounted } from 'vue'; function useDebounce(fn, delay) { let timer; const debouncedFn = () => { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { fn.apply(this, arguments); }, delay); }; return debouncedFn; } export default { setup() { const inputText = ref(''); const debouncedSearch = useDebounce((value) => { console.log('输入的内容:', value); }, 300); // 防抖延迟设置为300毫秒 onMounted(() => { inputText.value = ''; }); onMounted(() => { inputText.value = ''; }); return { inputText, debouncedSearch }; } } ``` 在模板中,你可以这样使用: ```html <input v-model="inputText" @input="debouncedSearch" /> ``` 这样,每当用户输入时,输入框绑定的 `@input` 事件会触发防抖函数 `debouncedSearch`,而不是直接触发 `search` 函数。只有当用户停止输入一段时间(这里是300毫秒)后,`debouncedSearch` 函数才会执行。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值