Vue.js - 将 JSON 对象写入本地文件 [英] Vue.js - Write JSON object to local file

查看:182
本文介绍了Vue.js - 将 JSON 对象写入本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不久前我开始学习 Vue.js,不久之后,我开始了一个更大的项目,但没有记住,Javascript 与本地文件系统交互的选项有限.我是通过vue-cli设置项目的,所以我必须通过npm start来启动网站.

上述项目包含一个用于 JSON 文件的可视化编辑器.当我想要实现保存按钮时,我意识到将 JSON 文件写入/保存(并且可能在未来读取)到我的本地机器是一项相当困难的任务.

我已经尝试过使用 node 的 fs 库,认为它可以工作,因为它是用 node.js 启动的.我还尝试了几个外部库,例如write-json-file npm 库.

我已经到了没有想法的地步,我几乎会做任何必要的事情来让它发挥作用.

解决方案

有 3 种方法可以做到这一点.

  1. 写入本地存储

  2. 创建一个 Blob 并调用一个事件来下载它

  3. 将其包装成一个电子应用程序并使用节点fs模块保存文件

我可以在这里向您展示这 3 个案例的示例

index.html

<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml"><头><meta charset="UTF-8"><title>Vue 测试</title><script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script><身体><div id="vue-app"><表格><input type="text" v-model="name"/>{{name}}<br/><input type="text" v-model="last"/>{{last}}<br/><input type="text" v-model="index"/>{{index}}<br/><选择 v-model="等级"><选项>5</选项><选项>6</选项><option>7</option><option>8</option><option>9</option><option>10</option></选择>{{年级}}<button type="button" v-on:click="add()">添加到表格</button><button type="button" v-on:click="saveFile()">saveFile</button></表单><表格边框=1"><thead><td>姓名</td><td>姓</td><td>索引</td><td>年级</td></thead><tr v-for="x in arr"><td>{{x.first}}</td><td>{{x.lastn}}</td><td>{{x.index}}</td><td>{{x.grade}}</td></tr></tbody>

<script src="test.js"></script>

test.js(写入本地存储)

新的 Vue ({el: '#vue-app',数据: {姓名: '',最后的: '',指数:0,等级:0,回声:[]},方法: {添加:功能(e){this.arr.push({first: this.name, lastn: this.last, index: this.index, grade: this.grade});控制台日志(1);},保存文件:函数(){const 数据 = JSON.stringify(this.arr)window.localStorage.setItem('arr', data);console.log(JSON.parse(window.localStorage.getItem('arr')))}});

创建一个 Blob 并调用一个事件来下载它

只更改 saveFile 函数

saveFile: function() {const 数据 = 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: function() {const 数据 = JSON.stringify(this.arr)const fs = require('fs');尝试 { fs.writeFileSync('myfile.txt', data, 'utf-8');}catch(e) { alert('保存文件失败!');}}

然后用Electron来包裹

电子 ./index.html

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.

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.

I already tried using node's fs library, thinking it would work, because it is launched with node. I also tried several external libraries e.g. the write-json-file npm 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.

解决方案

There are 3 ways to do this.

  1. Write to local storage

  2. Create a Blob and invoke an event to download it

  3. Wrap it into a electron app and use node fs module to save file

I can show you a sample here for these 3 cases

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 (Write to local storage)

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

only change for saveFile func

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 fs module to save file

Change for saveFile func

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 Electron to wrap it

electron ./index.html

这篇关于Vue.js - 将 JSON 对象写入本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆