【发布时间】:2020-06-25 11:08:05
【问题描述】:
我想为此将用户输入保存到 JSON 中,假设我有以下代码:
// saves data in to an object
saveData() {
let summaryValues = {
what: this.what.txt,
how: this.how.txt,
checkedValue: this.checked
};
this.savedValueArr.push(summaryValues);
},
//uses the array with the pushed object to append the JSON
saveAsJson() {
const fs = require("fs");
var content = JSON.stringify(this.savedValueArr);
fs.appendFile("testFile.json", content, err => {
if (err) console.log(err);
alert("File has been saved");
this.what.txt = "";
this.how.txt = "";
this.checked = "";
});
},
// reads JSON and pushs it to a variable
read() {
const fs = require("fs");
fs.readFile("testFile.json", "utf-8", (err, data) => {
if (err) {
alert("An error ocurred reading the file :" + err.message);
return;
}
// push parsed data back in to an array
let dataParse = JSON.parse(data);
this.test.push(dataParse);
});
}
read() 和 saveAsJson() 都是单击事件 saveAsJson 将单击时的数据保存在 testFile.json 中,read() 在单击时读取 testFile.json 并 我现在的第一个问题是我的 JSON 在我用两个数组填充后看起来像这样
[{"what":"test2","how":"test2","checkedValue":2},{"what":"test1","how":"test1","checkedValue":1}][{"what":"test2","how":"test2","checkedValue":2}]
我的第二个问题是,如果我关闭应用程序然后重新打开它并首先单击具有读取功能的按钮(以加载数据),然后填写字段并单击具有 saveAsJson 功能的按钮绑定到它我的 JSON 会覆盖旧保存的数据,并且只保存新数据。我不想发生这种情况。
如果有帮助,我会在 vue.js 中使用电子。
【问题讨论】: