[英]Trigger a watch function whenever any variable is changed in Vue.js
Is there a way I can trigger a Vue.js function whenever a variable within the app changed?有没有一种方法可以在应用程序中的变量发生变化时触发 Vue.js 函数?
var vm = new Vue({
el: '#demo',
data: {
variable1: 'Foo',
variable2: 'Bar',
.....
.....
variablen: 'Foo Bar'
},
watch: {
<<any variable>>: function(){
console.log('any of these variables changed');
}
}
})
First of all, I agree with all comments saying that 50 fields sound like a code smell and that code probably need to be refactored.首先,我同意所有评论,即 50 个字段听起来像是代码异味,并且可能需要重构代码。
Beside that, vue allows you to watch for whole data object
using $data
watch and explicitly set it as deep
除此之外,vue 允许您使用
$data
watch 监视整个data object
并将其显式设置为deep
watch: {
'$data': {
handler: function(newValue) {
console.log('Current vaules:' + newValue.FirstName + ' ' + newValue.LastName);
},
deep: true
}
}
Please see this working fiddle and this watch documentation extract请参阅此工作小提琴和此手表文档摘录
Option: deep
选项:深
To also detect nested value changes inside Objects, you need to pass in deep: true in the options argument.
要同时检测对象内部的嵌套值更改,您需要在选项参数中传递 deep: true 。 Note that you don't need to do so to listen for Array mutations.
请注意,您不需要这样做来侦听 Array 突变。
Warning警告
As @BelminBedak remarks, this example only demonstrates that it is possible to archive but not recommended for production environments.正如@BelminBedak 所说,此示例仅说明可以存档,但不建议将其用于生产环境。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.