data: function () {
return {
questions: []
}
},
watch: {
questions : function(val, oldVal) {
foo()
}
},
methods: {
foo() {
console.log("foo called");
}
}
Run Code Online (Sandbox Code Playgroud)
产生错误: ReferenceError: foo is not defined
我也在看例子:http://vuejs-ru.github.io/vuejs.org/api/options.html#watch
这个字符串做什么?
handler: function (val, oldVal) { /* ... */ },
handler它的关键字?或者它可以是功能?
nil*_*ils 21
如果您想使用手表来观察您的财产,您可以使用this.foo以下方法调用您的方法:
data: function () {
return {
questions: []
}
},
watch: {
questions: {
handler: function(val, oldVal) {
this.foo(); // call it in the context of your component object
},
deep: true
}
},
methods: {
foo() {
console.log("foo called");
}
}
Run Code Online (Sandbox Code Playgroud)
要回答您的问题handler:它是一个关键字属性,可以采用函数表达式(如示例中所示)或对函数的引用,例如:
function myHandler() { ... } // Defined somewhere outside of the vue component object
...
handler: myHandler,
...
Run Code Online (Sandbox Code Playgroud)
只是出于好奇:你是否需要观察一个属性,以便在每次更改时执行某些操作,或者计算属性也可以解决您的问题?
只是为了添加@nils 的答案
handler: 'foo'
Run Code Online (Sandbox Code Playgroud)
如果函数 foo 在方法中也有效。
比短一点
handler() {
this.foo()
}
Run Code Online (Sandbox Code Playgroud)