Javascript Vue.js - 将 JSON 对象写入本地文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48611671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue.js - Write JSON object to local file
提问by Phero
Some while ago I started learning Vue.js and a short while after, I started a bigger project, not keeping in mind, that Javascript has limited options to interact with the local file system.
I set up the project via vue-cli, so I have to start the website via npm start.
不久前我开始学习 Vue.js,不久之后,我开始了一个更大的项目,但没有记住,Javascript 与本地文件系统交互的选项有限。我通过 vue-cli 设置了项目,所以我必须通过npm start.
Said project consist of a visual editor for JSON Files. When I wanted to implement the save button, I recognized that it's a quite difficult task to make is write/save (and maybe read in the future) a JSON file to my local machine.
所述项目由 JSON 文件的可视化编辑器组成。当我想要实现保存按钮时,我意识到将 JSON 文件写入/保存(并且可能在未来读取)到我的本地机器是一项相当困难的任务。
I already tried using node's fslibrary, thinking it would work, because it is launched with node.
I also tried several external libraries e.g. the write-json-filenpm lib.
我已经尝试过使用 node 的fs库,认为它可以工作,因为它是用 node.js 启动的。我还尝试了几个外部库,例如write-json-filenpm lib。
I'm getting to a point where I'm out of ideas and would do pretty much anything thats necessary to make it work.
我已经到了没有想法的地步,并且会做几乎所有必要的事情来使它工作。
回答by yue you
There are 3 ways to do this.
有 3 种方法可以做到这一点。
Write to local storage
Create a Blob and invoke an event to download it
Wrap it into a electron app and use node
fsmodule to save file
写入本地存储
创建一个 Blob 并调用一个事件来下载它
将其包装成一个电子应用程序并使用节点
fs模块保存文件
I can show you a sample here for these 3 cases
我可以在这里向您展示这 3 种情况的示例
index.html
索引.html
<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Vue test</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
<div id="vue-app">
<form>
<input type="text" v-model="name"/>{{name}}<br/>
<input type="text" v-model="last"/>{{last}}<br/>
<input type="text" v-model="index"/>{{index}}<br/>
<select v-model="grade">
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
{{grade}}
<button type="button" v-on:click="add()">Add To Table</button>
<button type="button" v-on:click="saveFile()">saveFile</button>
</form>
<table border="1">
<thead><td>Name</td><td>Last Name</td><td>Index</td><td>Grade</td></thead>
<tbody>
<tr v-for="x in arr">
<td>{{x.first}}</td>
<td>{{x.lastn}}</td>
<td>{{x.index}}</td>
<td>{{x.grade}}</td>
</tr>
</tbody>
</table>
</div>
<script src="test.js"></script>
</body>
</html>
test.js (Write to local storage)
test.js(写入本地存储)
new Vue ({
el: '#vue-app',
data: {
name: '',
last: '',
index: 0,
grade: 0,
arr: []
},
methods: {
add: function (e) {
this.arr.push({first: this.name, lastn: this.last, index: this.index, grade: this.grade});
console.log(1);
},
saveFile: function() {
const data = JSON.stringify(this.arr)
window.localStorage.setItem('arr', data);
console.log(JSON.parse(window.localStorage.getItem('arr')))
}
});
Create a Blob and invoke a event to download it
创建一个 Blob 并调用一个事件来下载它
only change for saveFile func
仅更改 saveFile 功能
saveFile: function() {
const data = JSON.stringify(this.arr)
const blob = new Blob([data], {type: 'text/plain'})
const e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = "test.json";
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
Wrap it into an Electron app and use node fsmodule to save file
将其包装到一个 Electron 应用程序中并使用 nodefs模块来保存文件
Change for saveFile func
更改 saveFile 功能
saveFile: function() {
const data = JSON.stringify(this.arr)
const fs = require('fs');
try { fs.writeFileSync('myfile.txt', data, 'utf-8'); }
catch(e) { alert('Failed to save the file !'); }
}
Then use Electronto wrap it
然后用Electron包裹起来
electron ./index.html
electron ./index.html
回答by Yavor
This is how I edit JSON files in my Vue projects. In this case, if you run the file, it will create a new data.json file and add Price to each JSON object:
这就是我在 Vue 项目中编辑 JSON 文件的方式。在这种情况下,如果您运行该文件,它将创建一个新的 data.json 文件并将 Price 添加到每个 JSON 对象:
const fs = require("fs");
let cars = [
{
Name: "chevrolet chevelle malibu",
Miles_per_Gallon: 18,
Cylinders: 8,
Displacement: 307,
Horsepower: 130,
Weight_in_lbs: 3504,
Acceleration: 12,
Year: "1970-01-01",
Origin: "USA"
},
{
Name: "buick skylark 320",
Miles_per_Gallon: 15,
Cylinders: 8,
Displacement: 350,
Horsepower: 165,
Weight_in_lbs: 3693,
Acceleration: 11.5,
Year: "1970-01-01",
Origin: "USA"
}
];
cars.forEach(car => {
car.price = 12000;
});
let data = JSON.stringify(cars);
fs.writeFileSync("data.json", data);

