vue.js - watch 和 $watch 的区别

标签 vue.js vuejs3

只是一个简单的问题。
选项和实例方法有什么区别?
基于 watch 示例,我们可以将 watcher 实现为一个选项( https://v3.vuejs.org/api/options-data.html#watch )和一个实例的方法( https://v3.vuejs.org/api/instance-methods.html#watch )。
从我的理解来看,我可以使用这两种方法实现完全相同的功能,唯一的区别是语法和实现位置。
如果我弄错了,有人可以根据示例向我解释这两者之间的区别吗?

最佳答案

您的假设确实(几乎)是正确的。this.$watch()的两大优势尽管。

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

  • 但这并不一定意味着您应该始终使用 this.$watch()watch: {} .相反。您应该始终考虑您的用例需要什么
    取消监视示例:
    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.
    }
    //...
    
    }
    

    关于vue.js - watch 和 $watch 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69660082/

    相关文章:

    html - Vue.js 动态图像在 v-for 中不起作用

    typescript - 使用模板字符串预编译 TypeScript Vue 组件

    javascript - vue-class-component : Super expression must either be null or a function, 未定义

    typescript - 在 vue3 中使用 headless ui 的 Modal

    javascript - 如何在 JavaScript 中从外部 vue 应用程序调用自定义 Vue 3 方法?

    vue.js - Vue3 Pinia Store 在初始化之前无法访问 'store"

    mysql - 从 public/image 文件夹加载图像时禁止 403 laravel vuejs xampp

    javascript - 将输入值绑定(bind)到对象中的特定值

    javascript - 计算属性或数据以传递给背景图像的样式绑定(bind)

    javascript - 使用 Vuex 4 在 Vue 3 中设置状态数据不起作用