我正在使用 electronjs 和 sqlite3 学习,我也使用了 vue,当我尝试在 db.each 中执行 tb.push 时,消息是“未定义 this.tb”,我可以在不了解如何解决的情况下修复它
那么为什么下面的代码有效
var app=new Vue({
el:'#resultDiv',
data:{
message:'hi',
tb:[],
},
mounted(){
var tb=[];
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
db.serialize(function() {
db.run("CREATE TABLE lorem (info TEXT)");
var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
for (var i = 0; i < 10; i++) {
stmt.run("Ipsum " + i);
}
stmt.finalize();
var textee;
db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
textee=row.id + ": " + row.info;
console.log(textee);
tb.push(textee);
});
});
db.close();
this.tb=tb;
}
});
但这下面没有 var app=new Vue({
el:'#resultDiv',
data:{
message:'hi',
tb:[],
},
mounted(){
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
db.serialize(function() {
db.run("CREATE TABLE lorem (info TEXT)");
var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
for (var i = 0; i < 10; i++) {
stmt.run("Ipsum " + i);
}
stmt.finalize();
var textee;
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
});
});
db.close();
}
});
最佳答案
这是因为在您的非工作示例中
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
});
关键字this
不是指 vue 组件,而是指 each
的执行上下文-功能。这是由使用
function() {}
引起的。 - 描述匿名函数的方式。如果您改为使用箭头函数方式来表达回调:
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
现在指的是您的 vue 组件的执行上下文,您的代码应该可以工作。请注意,我必须对 serialize
使用箭头函数表达式。 -function 也一样,否则 this
会改为引用该函数执行上下文。备择方案
如果您由于某种原因不能使用箭头函数表达式,您有几种选择。您可以显式绑定(bind)
this
像这样的Vue上下文:db.serialize((function () {
db.each(..., (function (err, row) {
...
}).bind(this));
}).bind(this));
我不是特别喜欢这种方法。或者您可以捕获
this
在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);
});
}
关于sqlite - 执行 db.each 时未定义的 vue 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66490411/