【问题标题】:How to import a local stored xml file in Vue and edit it?如何在Vue中导入本地存储的xml文件并进行编辑?
【发布时间】:2018-11-22 19:25:38
【问题描述】:

我是 VueJS 的新手,现在想用 Vue JS 重写我的普通 Javascript SPA 的一部分(仅用于培训和学习)。 我使用 Vue-CLI 创建了我的项目。这是我现在文件结构的一部分:

---src
   |---assets
       |---logo.png
   |---components
       |---loadXML.vue
       |---table01.vue
       |---table02.vue
   |---static
       |---ABC.xml
   |---app.vue

我最近遇到了这个问题:

我想加载并读取一个本地存储的 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);

我可以通过xmlDoc做所有我需要做的事情

但是在 Vue JS 中,我发现加载和读取(解析)一个 xml 文件非常困难,即使我搜索了很多,我也找不到正确的方法来清理它。我已经尝试了以下方法:

(1)通过使用import直接将本地xml文件导入Vue:

import xmlFile from '../static/ABC.xml'

因为我可以直接导入本地json文件使用:

import jsonFile from '../static/XYZ.json'

但是它不适用于 xml 文件,我明白了:

Module parse failed. You may need an appropriate loader to handle this file type

(2) 借助 vue-resouce:

this.$http.get('../static/ABC.xml').then(function(data)) {
     var xmlDoc = data;
}

但后来我明白了:

http://localhost:8080/static/ABC.xml 404 (Not Found)

似乎相对路径在 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);

但我在 (2) 中遇到了同样的问题。所以我认为相对路径不适合 http 请求,因为需要以某种方式编译和重新组织文件。

我知道用 Vue JS 加载和读取甚至编辑 xml 文件是很少见的,但如果有人以前做过并指出我在这个阶段应该做什么,我将不胜感激。

【问题讨论】:

    标签: javascript vue.js xmlhttprequest vuejs2 vue-resource


    【解决方案1】:

    我使用 Axios:

    axios.get('http://localhost:8080/file.xml')
                    .then(response => {
                        var xmlText = response.data;
    });
    

    所以你把 xml 文件放在静态文件夹中,但是那个被认为是根文件夹。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-17
      • 2016-06-12
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多