vuejs导入导出文件

https://blog.csdn.net/Fabulous1111/article/details/80189112
摘自这篇博客 非常nice!
1.1、安装file-saver

1.2、使用file-saver
进入需要导出json文件的组件,使用file-saver

<template>
  <div class="hello">
    <button @click="exportJSON">导出jsonn</button>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
export default {
  data () {
    return {
      // 待导出的json数据
      CfgInfo: {
        CAN: {
          Chn: 0,
          name: 'CAN通道'
        },
        LIN: {
          Chn: 1,
          name: 'LIN通道'
        }
      }
    }
  },
  methods: {
    exportJSON () {
      // 将json转换成字符串
      const data = JSON.stringify(this.CfgInfo)
      const blob = new Blob([data], {type: ''})
      FileSaver.saveAs(blob, 'hahaha.json')
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
————————————————
版权声明:本文为CSDN博主「ECMAScripter」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Fabulous1111/article/details/80189112

导入导出json文件

<template>
  <div class="hello">
    <button @click="exportJSON">导出jsonn</button>
    <div>
      <input id="file" type="file" accept=".json"/>
      <button @click="importJSON">导入json</button>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
export default {
  data () {
    return {
      // 待导出的json数据
      CfgInfo: {
        CAN: {
          Chn: 0,
          name: 'CAN通道'
        },
        LIN: {
          Chn: 1,
          name: 'LIN通道'
        }
      },
      // 将导入的json保存在这个对象下
      ImportJSON: {}
    }
  },
  methods: {
    // 导出json
    exportJSON () {
      // 将json转换成字符串
      const data = JSON.stringify(this.CfgInfo)
      const blob = new Blob([data], {type: ''})
      FileSaver.saveAs(blob, 'hahaha.json')
    },
    // 导入json
    importJSON () {
      const file = document.getElementById('file').files[0]
      const reader = new FileReader()
      reader.readAsText(file)
      const _this = this
      reader.onload = function () {
        // this.result为读取到的json字符串,需转成json对象
        _this.ImportJSON = JSON.parse(this.result)
        // 检测是否导入成功
        console.log(_this.ImportJSON)
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
————————————————
版权声明:本文为CSDN博主「ECMAScripter」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Fabulous1111/article/details/80189112
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值