Skip to content

Vue中watch深度监听结合防抖的实践 ​

1. 业务场景 ​

在开发过程中遇到一个金额试算功能,需要根据用户的多个输入值实时调用后端接口进行计算。主要涉及以下四个参数:

  • 用户输入金额
  • 用户输入天数
  • 用户的信用卡信息(默认值)
  • 用户的借记卡信息(默认值)

2. 功能要求 ​

  • 信用卡和借记卡信息默认存在
  • 用户输入金额和天数时,需要实时进行试算
  • 仅当输入值符合业务规则时才调用接口:
    • 金额 ≥ 2000
    • 0 < 天数 ≤ 180

3. 实现思路 ​

为了避免频繁调用接口,使用防抖(debounce)处理用户输入。同时通过watch的深度监听来追踪参数变化。

4. 代码实现 ​

js
export default {
  data() {
    return {
      timer: null,
      amountMoney: 0,
      inputDate: 0
    }
  },

  computed: {
    params() {
      return {
        // 接口所需参数
        amount: this.amountMoney,
        days: this.inputDate,
        // ...其他参数
      }
    }
  },

  watch: {
    params: {
      handler(newValue, oldValue) {
        // 验证输入是否符合规则
        if (this.amountMoney >= 2000 && this.inputDate > 0 && this.inputDate <= 180) {
          // 防抖处理
          if (this.timer) {
            clearTimeout(this.timer)
          }
          
          this.timer = setTimeout(() => {
            this.getDailyFeeTrial() // 调用试算接口
            this.timer = null
          }, 1500)
        }
      },
      deep: true // 深度监听对象变化
    }
  },

  methods: {
    async getDailyFeeTrial() {
      // 试算接口调用逻辑
    }
  }
}

5. 核心要点 ​

  1. 使用 deep: true 实现对象的深度监听
  2. 使用防抖避免频繁调用接口
  3. 合理的参数验证确保接口调用的必要性

6. 注意事项 ​

  • 防抖时间设置为1.5秒,可根据实际业务需求调整
  • 注意清理定时器,避免内存泄漏
  • 参数验证条件可根据具体业务规则调整