Quentin_otd
Quentin_otd

Reputation: 233

Access Vue Instance Using this

When I try to use this in my VueJs methods I get the following error

this is undefined

I think that I shouldn't use arrow functions because their this does not bind to the context I expect it to.

I try with a regular function and get the error above.

What I've tried so far

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);
          });                   
   }
}

I cannot use the this that I want to in the functions passed to .search and .then . How can I have this bind to my VueJs instance so I can access data, computed, etc...?

Upvotes: 0

Views: 1078

Answers (2)

Styx
Styx

Reputation: 10086

You should use arrow function to save this context, and don't forget that inside Vue methods this refers to the current instance.

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);
    });
  }
}

Upvotes: 2

itsyub
itsyub

Reputation: 113

You can assign this variable to local variable(self) and use it in .then function

   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)

    }
}

Upvotes: 0

Related Questions