[Vuejs]-Undefined vue variable when executing db.each

0👍

This is because in your non-working example

db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
  textee=row.id + ": " + row.info;
  console.log(textee);
  this.tb.push(textee);//this not working
});

the keyword this doesn’t refer to the vue component, but to the execution context of the each-function.

This is caused by using the function() {}-way of describing anonymous functions.

If you’d instead use the arrow-function way to express the callback:

db.serialize(() => {
  db.each("SELECT rowid AS id, info FROM lorem", (err, row) => {
    textee=row.id + ": " + row.info;
    console.log(textee);
    this.tb.push(textee);//this now working
  });
});

this now refers to your vue component’s execution context and your code should work. Note that I had to use arrow function expression’s for the serialize-function as well, otherwise this would have referred to that functions execution context instead.

Alternatives

If you, for some reason, cannot use the arrow function expression, you have several alternatives. You could explicitly bind this to the vue context like so:

db.serialize((function () {
  db.each(..., (function (err, row) {
    ...
  }).bind(this));
}).bind(this));

I don’t particularly like this approach.

Or you could capture the this context in a variable under the closure of the mounted-method.

mounted() {
  var self = this;
  ...
  db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
    textee=row.id + ": " + row.info;
    console.log(textee);
    self.tb.push(textee);
  });
}

Leave a comment