有三种方法可以做到这一点。
写入本地存储
创建Blob并触发下载事件
将其包装成Electron应用程序,并使用node fs
模块保存文件
我可以在这里为这三种情况展示一个示例
index.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/vue@2.5.13/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 (写入本地存储)
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')))
}
});
创建 Blob 实例并触发事件以进行下载
仅更改 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);
}
将其封装成Electron应用程序,并使用node fs
模块保存文件。
更改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 !'); }
}
然后使用Electron将其包装
electron ./index.html