观看对象然后执行方法的Vuejs失败

问题描述 投票:2回答:1

我想看一个支柱,这是我的一个对象

<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显示新值,但我无法执行一个方法,因为在手表上收到错误观察者“回调”的回调错误:“TypeError:_this.fetchData不是一个函数”。如何在深度观察者上执行方法。

javascript vue.js vuejs2 watch
1个回答
2
投票

将箭头功能移动到handler method的简单功能。将handler:(newval)=> {更改为handler: function (newval) {

Vue.js docs:

不要在options属性或回调上使用箭头函数,例如created:()=> console.log(this.a)或vm。$ watch('a',newValue => this.myMethod())。

handler: function (newval) {
  console.log("i have new data",newval) //this works
  this.fetchData(); // it should work
},
© www.soinside.com 2019 - 2024. All rights reserved.