【问题标题】:watch(() => route.name,...) in Vue 3Vue 3 中的 watch(() => route.name,...)
【发布时间】:2021-12-26 11:46:05
【问题描述】:
https://stackoverflow.com/a/63800832/1497720

典型的监视语法是watch(<variable>, <function to handle>) 但在这个答案中:https://stackoverflow.com/a/63800832/1497720

我们有

watch(() => route.name, () => {
  console.debug(`MyCoolComponent - watch route.name changed to ${route.name}`);
  // Do something here...

  // Optionally you can set immediate: true config for the watcher to run on init
//}, { immediate: true });
});

谁能解释一下语法是什么意思?

【问题讨论】:

    标签: vue.js vuejs3


    【解决方案1】:

    监视助手的完整语法是:

    watch(param1,param2,param3)
    

    param1 可以是 ref 数据或返回另一个响应式数据(prop、计算或响应式 ...)的 getter 函数

    param2 是回调处理程序,它接受两个参数,新值和旧值

    param3 是观看选项,如{immediate:true,deep:true} 是可选的

    【讨论】:

    • 如果可以简单地使用返回值,那么使用 getter 函数的动机是什么?
    • 使用简单变量仅适用于ref数据,对于其他数据,您应该使用getter函数来触发观察者
    【解决方案2】:

    这只是使用 vm.$watch API 的另一种方式,请参考Vue documentation

    这里要带走的关键点是,您不仅可以查看数据或计算属性,还可以查看表达式。该表达式仅接受点分隔的路径。对于更复杂的表达式,请改用函数。

    这是一个例子:

    vm.$watch(
      function () {
        // every time the expression `this.a + this.b` yields a different result,
        // the handler will be called. It's as if we were watching a computed
        // property without defining the computed property itself
        return this.a + this.b
      },
      function (newVal, oldVal) {
        // do something
      }
    )
    

    所以在你上面的例子中,它可以简化为下面的这段代码:

    watch('route.name', () => {
      console.debug(`MyCoolComponent - watch route.name changed to ${route.name}`);
      // Do something here...
    
      // Optionally you can set immediate: true config for the watcher to run on init
    //}, { immediate: true });
    })
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2019-12-02
      • 2020-06-16
      • 2021-10-09
      • 2021-10-09
      • 2023-01-07
      • 2022-01-08
      • 2021-05-30
      • 2018-03-21
      相关资源
      最近更新 更多