watch与$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()有两个主要优势。

  1. 你可以开始动态观看
  2. this.$watch()的返回值是一个unwatch函数,可以在运行时动态停止监视器

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

Unwatch-example:

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()的合成API方法。

watch()的功能与watch: {}this.$watch()相同,也有一个unwatch-方法作为返回值。

watchEffect()检查参数(函数)内部提到的任何值,并在其内部放置一个监视器。

示例(合成)
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.
}
//...
}

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

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

这在optionsAPI中是不可能的。当应用程序中发生某些事情时,使用this.$watch返回的unwatch是非常有用的。

记住什么最适合你的用例,并相应地使用它

最新更新