当我尝试在VueJs方法中使用它时,出现以下错误
这是未定义的
我认为我不应该使用箭头函数,因为它们的this
不会绑定到我期望的上下文中。
我尝试使用常规函数并得到上面的错误。
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);
});
}
}
我无法在传递给this
和.search
的函数中使用想要的.then
。如何将this
绑定到我的VueJs实例,以便我可以访问data
,computed
等...?
答案 0 :(得分:1)
您可以将this
变量分配给局部变量( self )并在.then函数中使用
data () {
return {
counter:0,
connections:2
}
},
methods: {
connection(){
var self = this;
var tmp=0
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'xxxxxxxxxxxx'
});
client.search({
"index":"400000",
[...]
}
}).then(function (resp) {
var hits = resp.aggregations;
self.tmp=hits[1].value;
}, function (err) {
console.trace(err.message);
});
console.log("tmp:",tmp)
}
}
答案 1 :(得分:1)
您应该使用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);
});
}
}