console打印打印数据并下载打印的数据
前言
项目中经常使用到 console.log 进行调试打印数据,如果想下载 console 打印的数据,可进行如下配置:
配置
(function (console) {
console.save = function (data, filename) {
if (!data) {
console.error('Console.save: No data')
return;
}
if (!filename) filename = 'console.json'
if (typeof data === "object") {
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], { type: 'text/json' }),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
使用
console.save(需要打印的数据,导出的文件)
完整示例
<template>
<div style="margin: 100px">
<h3>console打印数据并下载为 json数据</h3>
<el-button @click="save">点击打印</el-button>
</div>
</template>
<script>
(function (console) {
console.save = function (data, filename) {
if (!data) {
console.error('Console.save: No data')
return;
}
if (!filename) filename = 'console.json'
if (typeof data === "object") {
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], { type: 'text/json' }),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
export default {
name: "index.vue",
data(){
return {
list:[
{label:'测试1',value:1},
{label:'测试2',value:2}
]
}
},
methods:{
save(){
console.log('数据:', this.list)
console.save(this.list,'test.json')
}
}
}
</script>
<style scoped>
</style>