vue.js - watch 和 $watch 的区别
问题描述
只是一个简单的问题。
选项和实例方法有什么区别?
基于 watch 示例,我们可以将 watcher 实现为一个选项(https://v3.vuejs.org/api/options-data.html#watch)和一个实例的方法(https://v3.vuejs.org /api/instance-methods.html#watch)。
根据我的理解,我可以用这两种方法实现完全相同的功能,唯一的区别是语法和实现的位置。
如果我弄错了,有人可以根据示例向我解释这两者之间的区别吗?
解决方案
你的假设确实(几乎)是正确的。
虽然有2个主要优势this.$watch()
。
- 您可以开始动态观看
- 的返回值
this.$watch()
是一个 unwatch 函数,您可以使用它在运行时动态停止观察者
但这并不一定意味着您应该始终使用this.$watch()
over 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()
组合 API方法。
watch()
与 and做同样的事情watch: {}
,this.$watch()
并且还有一个 unwatch 方法作为返回值。
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.
}
//...
}
推荐阅读
- jpa - 如何在 glassfish-resource.xml [Pyara] 中添加多个连接池
- calculated-field - (Quicksight)如何在按月分组时对“按日不同计数”的每个值求和
- gnuplot - 如何告诉 gnuplot 为 ytics 显示更多数字?
- javascript - Angular Async 管道在单元测试中没有正确更新
- c# - 如何在 xUnit 中设置 cookie
- javascript - 如何获取类别的值,然后将其显示在另一个文本框中
- python - 有没有更简洁的方法将 kwargs 从类传递给函数
- php - 如何从使用 Symfony 的构建器类中捕获我的控制器中的数据
- python - 如何对齐标签?Python
- javascript - Bitcore-lib 签名交易出错