• 技术文章 >web前端 >Vue.js

    vue怎么读取文件内容

    藏色散人藏色散人2021-09-02 14:46:56原创298

    vue读取文件内容的方法:1、创建一个test.properties测试内容;2、通过“readTestFile(){const file = this.loadFile('test.properties')...}”方法读取文件内容即可。

    本文操作环境:windows7系统、vue/cli 4.3.1&&ultimate 2019.1&&nodev12.16.2版,DELL G3电脑。

    观前提示:

    本文所使用的IDEA版本为ultimate 2019.1,node版本为v12.16.2,vue版本为@vue/cli 4.3.1。

    在项目开发过程中,需要在vue前端读取配置等文件。

    1.实例

    我的本地文件放在vue项目中的public文件夹中

    在这里插入图片描述

    test.properties

    content=测试内容

    vue文件中读取文件内容

    // 读取test.properties
    readTestFile() {
      const file = this.loadFile('test.properties')
      console.info(file)
      console.log(this.unicodeToUtf8(file))},
      // 读取文件
      loadFile(name) {
      const xhr = new XMLHttpRequest()
      const okStatus = document.location.protocol === 'file:' ? 0 : 200
      xhr.open('GET', name, false)
      xhr.overrideMimeType('text/html;charset=utf-8')
      // 默认为utf-8
      xhr.send(null)
      return xhr.status === okStatus ? xhr.responseText : null},
      // unicode转utf-8
      unicodeToUtf8(data) {
      data = data.replace(/\\/g, '%')
      return unescape(data)}

    运行结果如下
    在这里插入图片描述

    2.可能遇到的问题

    2.1.解析的文件乱码

    读取文件的方法,以utf-8形式读取文件,建议修改文件格式保存为utf-8编码,或者改变读取格式

    xhr.overrideMimeType('text/html;charset=utf-8')
    // 默认为utf-8

    2.2.读取中文为unicode编码

    由于properties存储中文为unicode编码,需要在后台,或者前端处理一下

    // unicode转utf-8
    unicodeToUtf8(data) {
      data = data.replace(/\\/g, '%')
      return unescape(data)}

    相关推荐:《vue.js教程

    以上就是vue怎么读取文件内容的详细内容,更多请关注php中文网其它相关文章!

    声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
    专题推荐:vue
    上一篇:vuejs是什么时候出来的 下一篇:怎么离线安装vue环境
    大前端线上培训班

    相关文章推荐

    • Vue this.$set为data中的某一对象添加一个属性• 浅析vue中web前端项目优化(附代码)• 一文介绍sublime text3搞定vue文件模板• vue传参的三种方式是什么

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网