当我尝试在 VueJs 方法中使用它时,出现以下错误
this is undefined
我认为我不应该使用箭头函数,因为它们的 this
没有绑定(bind)到我期望的上下文。
我尝试使用常规函数并得到上面的错误。
到目前为止我尝试过的内容
methods: {
connection(){
new elasticsearch.Client({...});
client.search({...})
.then(function (resp) {
var hits = resp.aggregations;
this.tmp = hits[1].value;
}, function (err) {
console.trace(err.message);
});
}
}
我无法在传递给 .search
和 .then
的函数中使用我想要的 this
。如何将 this
绑定(bind)到我的 VueJs 实例,以便我可以访问数据
、计算
等...?
最佳答案
您应该使用arrow function保存 this
上下文,并且不要忘记在 Vue 方法内部 this
引用当前实例。
data() {
return {
counter:0,
connections:2,
tmp: 0,
}
},
methods: {
connection() {
// ...
var client = new elasticsearch.Client({
host: 'xxxxxxxxxxxx'
});
client.search({
[...]
}).then((resp) => {
var hits = resp.aggregations;
this.tmp = hits[1].value;
}, (err) => {
console.trace(err.message);
});
}
}
关于javascript - 使用此访问 Vue 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55567884/