1、NPM安装x2js
npm i x2js
2、在main.js
引入
import x2js from ‘x2js’
Vue.prototype.$x2js = new x2js()
3、定义一个组件,把一下代码复制进去,引入组件即可
<template>
<div class="file-button-box">
<a-button class="add" @click="add"> 新建 </a-button>
<a-button class="save"> 保存 </a-button>
<a-button class="save-as"> 另存 </a-button>
<a-button class="load" @click="load"> 加载 </a-button>
<input
type="file"
v-show="false"
ref="loadInput"
@change="fileChange"
id="uoload-xml"
/>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
add() {
console.log(666);
},
load() {
this.$refs.loadInput.click();
},
fileChange(event) {
console.log(event);
let xmlList = event.target.files;
let file = document.getElementById("uoload-xml");
for (var i = 0; i < xmlList.length; i++) {
let num = xmlList[i].name.split(".");
let mun = num[num.length - 1];
if (mun === "xml") {
this.parseXML(i);
} else {
alert("当前上传文件中有非XML格式的文件");
file.outerHTML = file.outerHTML;
}
}
},
parseXML(index) {
let file = document.getElementById("uoload-xml").files[index];
let reader = new FileReader();
reader.readAsText(file, "gutf-8"); //注意读取中文的是用这个编码,不是utf-8
if (typeof FileReader === "undefined") {
alert("您的浏览器不支持FileReader接口");
}
reader.onload = (e) => {
let js = this.$x2js.xml2js(e.target.result);
console.log(js, "这里");
this.$emit("getXmlData", js);
};
},
},
};
</script>
<style lang="less" scoped>
.file-button-box {
position: absolute;
z-index: 1000000;
left: 0;
top: 20px;
display: flex;
flex-direction: column;
width: 80px;
height: 200px;
justify-content: space-around;
padding: 3px;
.ant-btn {
border: 2px solid #52666b;
color: #000000;
}
.add {
background-color: #3fd2f9;
}
.save {
background-color: #01f0c3;
}
.save-as {
background-color: #c4f205;
}
.load {
background-color: #ff7011;
}
}
</style>