Vue.js - Write JSON object to local file

前端 未结 2 2051
暖寄归人
暖寄归人 2020-12-14 10:04

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 l

2条回答
  •  遥遥无期
    2020-12-14 10:40

    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

    
    
    
        
        Vue test
        
    
    
    
    {{name}}
    {{last}}
    {{index}}
    {{grade}}
    NameLast NameIndexGrade
    {{x.first}} {{x.lastn}} {{x.index}} {{x.grade}}

    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

提交回复
热议问题