Vue2API监听

222 阅读1分钟

有的时候会动态创建监听

动态创建监听,选项式API的watch选项就没用了

就需要使用Vue提供的$watch函数动态创建监听,当然,这个创建的监听,监听的数据也必须是响应式,毕竟在底层,选项式API的watch也是用这个创建监听的。

定义

$watch(
  expOrFn: string,
  callback: (this: this, n: any, o: any) => void,
  options?: WatchOptions
): (() => void);
$watch<T>(
  expOrFn: (this: this) => T,
  callback: (this: this, n: T, o: T) => void,
  options?: WatchOptions
): (() => void);

这个是一个函数重载,表示

  • 第一个参数可以是字符串,也可以是一个函数
  • 第二参数就是handle了
  • 第三参数就是选项了

返回一个取消监听的函数

第一种类型

<template>
  <div>
    API监听
    {{data}}
    <el-button @click="cancelWatch">取消监听</el-button>
  </div>
</template>

<script>
export default {
  data(){
    return{
      data:1,
      watch: null
    }
  },
  created() {
    this.watch = this.$watch('data',()=>{
      setTimeout(()=>{
        this.data++
      },1000)
    },{
      immediate: true
    })
  },
  methods:{
    cancelWatch(){
      if(this.watch){
        this.watch()
      }
    }
  }
}
</script>

<style scoped>

</style>

这样就创建了一个监听,点击取消按钮执行取消函数这个监听就失效了

2023-03-07-17-04-06.gif

第二种方式

<template>
  <div>
    API监听
    {{data}}
    <el-button @click="cancelWatch">取消监听</el-button>
  </div>
</template>

<script>
export default {
  data(){
    return{
      data:1,
      watch: null
    }
  },
  created() {
    this.watch = this.$watch(()=>{
      return this.data
    },()=>{
      setTimeout(()=>{
        this.data++
      },1000)
    },{
      immediate: true
    })
  },
  methods:{
    cancelWatch(){
      if(this.watch){
        this.watch()
      }
    }
  }
}
</script>

<style scoped>

</style>

在函数中返回这个要监听的就可以创建成功,和第一种没有太大的区别

最后

API创建的监听并不需要在组件销毁的时候去调用一下返回的函数,vue会帮我们处理