Min*_*XIE 6 javascript xmlhttprequest vue.js vue-resource vuejs2
我是 VueJS 的新手,现在想用 Vue JS 重写我的纯 Javascript SPA 的一部分(仅用于培训和学习)。我使用 Vue-CLI 创建了我的项目。现在这是我的文件结构的一部分:
---src
|---assets
|---logo.png
|---components
|---loadXML.vue
|---table01.vue
|---table02.vue
|---static
|---ABC.xml
|---app.vue
Run Code Online (Sandbox Code Playgroud)
我最近在这个问题上苦苦挣扎:
我想将本地存储的 xml 文件(在静态文件夹中)加载并读取到 Vue 实例中,然后解析它并对其进行一些编辑。
在我的普通 Javascript 中,通过使用以下方法可以非常简单地做到这一点:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var xmlDoc = this.responseXML;
}
}
xhttp.open('GET', 'ABC.xml', true);
Run Code Online (Sandbox Code Playgroud)
我可以做我需要做的一切xmlDoc
但在 Vue JS 中,我发现加载和读取(解析)xml 文件非常困难,即使我搜索了很多,我也找不到正确的方法来清理它。我已经尝试过以下方法:
(1)通过使用import直接将本地xml文件导入到Vue中:
import xmlFile from '../static/ABC.xml'
Run Code Online (Sandbox Code Playgroud)
因为我可以使用以下命令直接导入本地json文件:
import jsonFile from '../static/XYZ.json'
Run Code Online (Sandbox Code Playgroud)
但它不适用于 xml 文件,我得到了这个:
Module parse failed. You may need an appropriate loader to handle this file type
Run Code Online (Sandbox Code Playgroud)
(2)借助vue-resouce:
this.$http.get('../static/ABC.xml').then(function(data)) {
var xmlDoc = data;
}
Run Code Online (Sandbox Code Playgroud)
但后来我得到了这个:
http://localhost:8080/static/ABC.xml 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)
看起来相对路径在 http 请求中不起作用。
(3) 使用VueJS中的旧代码:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var xmlDoc = this.responseXML;
}
}
xhttp.open('GET', '../static/ABC.xml', true);
Run Code Online (Sandbox Code Playgroud)
但我在(2)中遇到了同样的问题。所以我认为相对路径不适合 http 请求,因为文件需要以某种方式进行编译和重新组织。
我知道使用 Vue JS 加载和读取甚至编辑 xml 文件的情况很少见,但如果有人以前做过并指出我在这个阶段应该做什么,我将不胜感激。
小智 2
我使用axios:
axios.get('http://localhost:8080/file.xml')
.then(response => {
var xmlText = response.data;
});
Run Code Online (Sandbox Code Playgroud)
因此,您将 xml 文件放在 static 文件夹中,但该文件夹被视为根文件夹。
| 归档时间: |
|
| 查看次数: |
9477 次 |
| 最近记录: |