无法访问监视处理程序 vuejs 中的数据变量 [英] can't access data variables in watch handler vuejs

查看:31
本文介绍了无法访问监视处理程序 vuejs 中的数据变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to set a data variable in a watch handler function for an input field in a VueJs Component. I have something like this:

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.params 得到一个 undefined,并且我在尝试设置 this.params.from 时遇到错误.所以我尝试使用一种方法访问它:

When I set an input for the dates variable in the view template, I get an undefined for this.params in the console log, and I get an error for trying to set this.params.from. So I tried accessing it using a method:

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

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

calling it in the view template, it correctly resolves the params object.

我在这里遗漏了什么吗?

Am I missing something here?

推荐答案

为了避免额外绑定,请避免在此处使用箭头函数语法.而是使用 ES6 Object 简写:

To avoid additional binding, just avoid using the arrow function syntax here.Instead go with ES6 Object shorthands:

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 将默认绑定到正确的上下文.

Now this will be bound to the correct context by default.

这篇关于无法访问监视处理程序 vuejs 中的数据变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆