1 安装插件
npm install json2csv --save
2 导入插件
import json2csv from 'json2csv'
3 实现
<template>
<div id="app">
<button @click="download()">csv</button>
</div>
</template>
<script>
import json2csv from 'json2csv'
export default {
name: 'App',
data() {
return {
datas: [
{
column1: 'value1',
column2: 'value2',
column3: 'value3'
},
{
column1: 'value4',
column2: 'value5',
column3: 'value6'
}
],
fields: ['column1','column2','column3']
}
},
components: {
},
methods: {
download(){
//datas:数据,fields:字段名
try {
const result = json2csv.parse(this.datas, {
fields: this.fields
});
// 判断浏览器类型
if ((navigator.userAgent.indexOf('compatible') > -1 &&
navigator.userAgent.indexOf('MSIE') > -1) ||
navigator.userAgent.indexOf('Edge') > -1) {
//IE10或Edge浏览器
var BOM = "\uFEFF";
var csvData = new Blob([BOM + result], { type: "text/csv" });
navigator.msSaveBlob(csvData, `test.csv`);
} else {
//非IE浏览器
var csvContent = "data:text/csv;charset=utf-8,\uFEFF" + result;
//使用a标签的download属性实现下载功能
var link = document.createElement("a");
link.href = encodeURI(csvContent);
link.download = `test.csv`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
} catch (err) {
alert(err);
}
}
}
}
</script>