我想看一个 Prop ,它是一个物体,所以我有
<script>
export default {
watch:{
filter: {
handler:(newval)=> {
console.log("i have new data",newval) //this works
this.fetchData(); //throws an error
},
deep: true
}
},
props:{
filter:{
type:Object,
required:true
}
},
data: () => ({
pagination: {},
items: []
}),
methods:{
fetchData(){
console.log("am fetching the data");
}
}
}
上面的观察者在 console.log 显示新值时工作,但我无法执行方法,因为在 watch 上我收到错误观察者“filter”的回调错误:“TypeError:_this.fetchData 不是函数” .我如何在深度观察者上执行一个方法。
最佳答案
将箭头函数移动到处理程序方法
的简单函数。将 handler:(newval)=> {
更改为 handler: function (newval) {
:
Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()).
handler: function (newval) {
console.log("i have new data",newval) //this works
this.fetchData(); // it should work
},
关于javascript - Vuejs 观察一个对象然后执行一个方法失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55198329/