Home > Web Front-end > Vue.js > How to read file content in vue

How to read file content in vue

藏色散人
Release: 2023-01-13 00:45:24
Original
16635 people have browsed it

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

How to read file content in vue

本文操作环境: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文件夹中

How to read file content in vue

test.properties

content=测试内容
Copy after login

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)}
Copy after login

运行结果如下
How to read file content in vue

2.可能遇到的问题

2.1.解析的文件乱码

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

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

2.2.读取中文为unicode编码

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

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

相关推荐:《vue.js教程

The above is the detailed content of How to read file content in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
vue
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template