Vue watch 监听手机号输入完毕后请求数据

Bac: 需要在用户输入手机号之后,调用后台接口去获取对应该手机号的数据情况

思路是:监听用户输入手机号,当输入的手机号长度 = 11 的时候,此时再去请求接口。

在这里监听学习到了两种方式:

一、watch 监听 计算属性的值

watch:{
          customerMobile (val, oldval) {
            if (val.length === 11) {
              this.handleCustomerChange(val)
            }
            // clearTimeout(this.timeout)
            //   this.timeout = setTimeout(() => {
            //     this.handleCustomerChange(val)
            //   }, 500)
          }
        },
 computed : {
          customerMobile () {
            return this.addForm.mobile
          }
    },
  methods: {
          // 输入手机号,客户名称联系人联动
          handleCustomerChange(){
            this.$http.get(`${window.SITE_CONFIG['baseURL']}/presale/presalelist/getDataByMobile`,
            {
              params:{
                mobile: this.addForm.mobile
              }
            })
            .then(data => {
              if (data.result.code === 0){
                this.addForm.username = data.result.data.customerName
                this.addForm.linkman = data.result.data.name
              } else {
                this.$message({
                  message: data.result.msg,
                  type: 'error',
                  duration: 1500
                })
              }
            })
          }
}
 

二、watch直接监听某个对象的属性

watch:{
          'addForm.mobile' : function(val, oldval){
              if (val.length === 11) {
              this.handleCustomerChange(val)
            }
          }
       },
原文地址:https://www.cnblogs.com/rabbit-lin0903/p/12665400.html