无法访问监视处理程序 vuejs 中的数据变量

can't access data variables in watch handler vuejs

我正在尝试在监视处理函数中为 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 变量设置输入时,我在控制台日志中得到 this.paramsundefined,并且我在尝试设置 this.params.from。所以我尝试使用一种方法访问它:

methods: {
    printParams() {
        console.log(this.params)
    }
}

在视图模板中调用它,它正确地解析了 params 对象。

我是不是漏掉了什么?

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

        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")
            }
        }.bind(this)

为避免额外的绑定,只需避免使用箭头函数语法here.Instead使用 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 将默认绑定到正确的上下文。