问题描述
我正在尝试在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
}
}
当我设置输入时对于视图模板中的日期
变量,我得到未定义
this.params
在控制台日志中,我在尝试设置 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对象缩写:
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
}
}
现在此
将被绑定t o默认情况下正确的上下文。
Now this
would be binded to correct context by default.
这篇关于无法访问监视处理程序vuejs中的数据变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!