javascript - 使用此访问 Vue 实例

标签 javascript vue.js

当我尝试在 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/

相关文章:

javascript - 如何在点击链接时执行 Ajax 代码?

javascript - 如何删除 angularfire2 中的链接引用?

javascript - 替换某一点之前的所有文本

javascript - vue.js 使用 $options 在过滤器中传递参数

javascript - 使用 Vue 和 HTML 在 JavaScript 中制作幻灯片,但图像出现错误 404 "Not found"

javascript - 元素 $(this) 在 console.log 中输出不同的格式

javascript - 数据表列过滤器文本范围搜索

node.js - 无法运行 > Laravel 上的 npm run watch

javascript - Vuex 2.0 Dispatch 与 Commit

javascript - 视觉 : "_" prefixed property not working in data property