data: function () {
return {
questions: []
}
},
watch: {
questions : function(val, oldVal) {
foo()
}
},
methods: {
foo() {
console.log("foo called");
}
}
产生错误:ReferenceError: foo is not defined
我也在看例子:http://vuejs-ru.github.io/vuejs.org/api/options.html#watch
这个字符串做什么?
handler: function (val, oldVal) { /* ... */ },
handler
这是关键字吗?或者它可以起作用?
答案 0 :(得分:16)
如果您想使用手表观察您的财产,可以使用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");
}
}
回答关于handler
的问题:这是一个关键字属性,可以采用函数表达式(如示例中所示)或对函数的引用,例如:
function myHandler() { ... } // Defined somewhere outside of the vue component object
...
handler: myHandler,
...
出于好奇:您是否需要观看某个属性,以便每次更改时都可以执行某项操作,或者computed properties也可以解决您的问题?
答案 1 :(得分:2)
只需添加到@nils的答案中即可
handler: 'foo'
如果功能foo在方法之内,则也可以使用。
比...短
handler() {
this.foo()
}