无法访问监视处理程序vuejs

时间:2017-04-27 07:19:58

标签: javascript vue.js vuejs2 vue-component

我正在尝试在VueJs组件中的输入字段的监视处理函数中设置数据变量。我有这样的事情:

data() {
    return {
        params: {
            // default params to 1 month
            from: new Date().setMonth(new Date().getMonth() - 1),
            to: Date.now(),
            skip: 0,
            limit: 100
        }
    }
}
watch: {
    dates: { 
        handler: date => {
            console.log(this.params)
            if (date.start) {
                this.params.from = moment(date.start, "YYYY/MM/DD")
            }
            if (date.end) {
                this.params.to = moment(date.end, "YYYY/MM/DD")
            }
        },
        deep: true
    }
}

当我在视图模板中为dates变量设置输入时,我在控制台日志中得到undefined this.params,并且在尝试设置{时遇到错误{1}}。所以我尝试使用一种方法访问它:

this.params.from

在视图模板中调用它,它正确地解析了methods: { printParams() { console.log(this.params) } } 对象。

我在这里错过了什么吗?

2 个答案:

答案 0 :(得分:11)

为了避免额外的绑定,请避免在此使用箭头函数语法。而不是使用ES6对象的缩写:

watch: {
    dates: { 
        handler(date) {
            console.log(this.params)
            if (date.start) {
                this.params.from = moment(date.start, "YYYY/MM/DD")
            }
            if (date.end) {
                this.params.to = moment(date.end, "YYYY/MM/DD")
            }
        },
        deep: true
    }
}

默认情况下,this绑定到正确的上下文。

答案 1 :(得分:1)

让我们尝试bind这个给你的处理程序

  declare var cordova: any;

  export class MyApp {

  constructor(platform: Platform ) {
    platform.ready().then(() => {
       console.log(cordova.plugins.uid.IMEI);
    });
  }