watch 侦听器(监视器)

79 阅读1分钟

作用:监视数据变化,执行一些 业务逻辑 或 异步操作。

语法:

① 简单写法 → 简单类型数据,直接监视

data: {
  words: '苹果',
  obj: {
    words: '苹果'
     }
   },
watch: {
// 该方法会在数据变化时,触发执行
数据属性名 (newValue, oldValue) {
   一些业务逻辑 或 异步操作。
},
'对象.属性名' (newValue, oldValue) {
   一些业务逻辑 或 异步操作。
  }
}
const app = new Vue({
        el: '#app',
        data: {
          // words: ''
          obj: {
            words: ''
          }
        },
        // 具体讲解:(1) watch语法 (2) 具体业务实现
        watch: {
          // 该方法会在数据变化时调用执行
          // newValue新值, oldValue老值(一般不用)
          // words (newValue) {
          //   console.log('变化了', newValue)
          // }

          'obj.words' (newValue) {
            console.log('变化了', newValue)
          }
        }
      })

② 完整写法 → 添加额外配置项(深度监视复杂类型,立刻执行)

  1. deep: true 对复杂类型深度监视

  2. immediate: true 初始化立刻执行一次handler方法

data: {
  obj: {
  words: '苹果',
  lang: 'italy'
  },
},
watch: {// watch 完整写法
  数据属性名: {
     deep: true, // 深度监视
     immediate: true, // 是否立刻执行一次handler
     handler (newValue) {
       console.log(newValue)
     }
   }
}
const app = new Vue({
        el: '#app',
        data: {
        // words: ''
          obj: {
            words: '',
          },
          result: '', // 翻译结果
          // timer: null // 延时器id
        },
        watch: {
          // 该方法会在数据变化时调用执行
          // newValue新值, oldValue老值(一般不用)
          // words (newValue) {
          //   console.log('变化了', newValue)
          // }

          // 'obj.words' (newValue) {
          // console.log('变化了', newValue)
          // 防抖: 延迟执行 → 干啥事先等一等,延迟一会,一段时间内没有再次触发,才执行
          //   clearTimeout(this.timer)
          //   this.timer = setTimeout(async () => {
          //     const res = await axios({
          //       url: 'https://applet-base-api-t.itheima.net/api/translate',
          //       params: {
          //         words: newValue
          //       }
          //     })
          //     this.result = res.data.data
          //     console.log(res.data.data)
          //   }, 300)
          // }
          
           obj: {
            deep: true, // 深度监视
            immediate: true, // 立刻执行,一进入页面handler就立刻执行一次
            handler (newValue) {
              clearTimeout(this.timer)
              this.timer = setTimeout(async () => {
                const res = await axios({
                  url: 'https://applet-base-api-t.itheima.net/api/translate',
                  params: newValue
                })
                this.result = res.data.data
                console.log(res.data.data)
              }, 300)
            }
          }

        }
      })