下面以vue为例,首先我想要读取一个vue的文件(其他格式也一样)的内容赋值在变量上然后传给组件,js参考下也是可以使用的。
第一步:先新建text.vue测试文件。我放在了public目录下的other目录下。
第二步:获取静态文件
第三步:获取输出结果,查看是否成功
此时我们已经拿到vue文件的值了,下面要看下传入子组件中页面是否正常。
第四步:检测效果
好了,拿捏妥妥的,下面上代码,经常看别人的经验,由衷感觉只发图片不上代码就是在耍流氓。
代码区域:直接调用readTestFile函数即可,记得this.loadFile('other/test.vue')里面要写需要读取的静态文件路径
// 读取test.properties
readTestFile() {
const file = this.loadFile('other/test.vue');
console.info(file);
console.log(this.unicodeToUtf8(file));
this.data = 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);
},