【问题标题】:Difference between watch and $watchwatch 和 $watch 的区别
【发布时间】:2021-12-08 02:33:46
【问题描述】:

只是一个简单的问题。

选项和实例方法有什么区别?

基于 watch 示例,我们可以将 watcher 实现为选项 (https://v3.vuejs.org/api/options-data.html#watch) 和实例方法 (https://v3.vuejs.org/api/instance-methods.html#watch)。

根据我的理解,我可以用这两种方法实现完全相同的功能,唯一的区别是语法和实现位置。

如果我弄错了,有人可以根据示例向我解释这两者之间的区别吗?

【问题讨论】:

    标签: vue.js vuejs3


    【解决方案1】:

    您的假设确实(几乎)正确。

    this.$watch() 有两个主要优势。

    1. 您可以开始动态观看
    2. this.$watch() 的返回值是一个 unwatch 函数,您可以使用它在运行时动态停止观察者

    但这并不一定意味着您应该始终使用this.$watch() 而不是watch: {}。相反。您应该始终考虑您的用例需要什么

    Unwatch 示例:

    export default {
    //..
    created(props) {
      const unwatchAge = this.$watch(() => this.user.age, (value, oldValue) => {
        if (value >= 18) {
          alert('You are now allowed to drive a car!');
          unwatchAge(); //we don't need age watching for anything else
        }
      });
    }
    //...
    
    }
    

    顺便说一句,使用 VUE3,您可能想研究 watch() / watchEffect() composition API 方法。

    watch() 与 watch: {} 和 this.$watch() 的作用相同,并且还有一个 unwatch-method 作为返回值。

    watchEffect() 检查参数(函数)中提到的任何值并在内部放置一个观察者。

    watch() 示例(作文)

    import { toRef, watch} from 'vue';
    
    export default {
    //...
    setup(props) {
      const age = toRef(props.age);
      const unwatchAge = watch(age, console.log); 
      // no () => age or () => age.value needed as age is a reference by using toRef and references can be handles like this
    
      setTimeout(() => {
        console.warn('unwatching age!');
        unwatchAge();
      }, 5000);
    }
    //...
    
    }
    

    watchEffect() 示例(作文)

    import { toRef, watchEffect} from 'vue';
    
    export default {
    //...
    setup(props) {
      const age = toRef(props.age);
      
      watchEffect(() => {
        if (age.value >= 18) {
          alert('You are now allowed to drive a car!');
        }
      });
      //vue will internally recognize that age has to be watched here. No telling it manually.
    }
    //...
    
    }
    

    【讨论】:

      【解决方案2】:

      与文档的主要区别在于instance method 返回一个unwatchable,您可以触发它来停止观看某个属性:

      const unwatchUsers = this.$watch('users', () => {});
      
      setTimeout(unwatchUsers, 1000);
      

      options API 无法做到这一点。当您的应用发生某些事情时,使用由this.$watch 返回的unwatch 非常有用。

      记住最适合您的用例并相应地使用它

      【讨论】:

        猜你喜欢
        • 2017-10-22
        • 1970-01-01
        • 2018-02-27
        • 2013-01-30
        • 2016-10-31
        • 1970-01-01
        • 2017-09-26
        • 2017-12-23
        相关资源
        最近更新 更多