假设对象数组格式为此
arr1: [{id: 1,title: '我是1目录',children: [{id: 11,title: '我是1-1目录',children: [{id: 111,title: '我是1-1-1目录',children: [],},],},],},{id: 2,title: '我是2目录',children: [{id: 21,title: '我是2-1目录',children: [],},],},],
页面如下
先在页面上添加按钮点击事件,事件函数如下
参数dataRef就是对象数组的格式
function exportTXT(dataRef) {let arrayChildren = [];arrayChildren.push(dataRef);let dimenData = flatten(arrayChildren);let fileData = [];dimenData.map((item) => {fileData.push(item.title);});const fileName = '导出文件.txt';const csvContent = fileData.map((row) => `${row}`).join('\n');const blob = new Blob([csvContent], { type: 'text/csv' });const url = URL.createObjectURL(blob);const link = document.createElement('a');link.href = url;link.download = fileName;document.body.appendChild(link);link.click();}function flatten(arr) {return [].concat(...arr.map((item) => [].concat(item, ...flatten(item.subitems))));}
结果:
详细代码如下(功能是展示树结构的目录 右键导出txt):
需要把treeData换成上面的数组
去掉这个代码
<template><div style="border: 1px solid rgb(23, 106, 150)"><div style="font-size: 16px; color: white; padding: 10px; background-color: rgb(23, 106, 150)">{{ title }}</div><a-tree :treeData="treeData"><template #title="{ key: treeKey, title, dataRef }"><a-dropdown :trigger="['contextmenu']"><span>{{ title }}</span><template #overlay><a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)"><a-menu-item key="1" @click="exportTXT(dataRef)">导出TXT</a-menu-item><a-menu-item key="2" @click="exportTXT(dataRef)">导出PDF</a-menu-item></a-menu></template></a-dropdown></template></a-tree></div>
</template><script>import { onMounted, reactive, toRefs } from 'vue';// import { saveAs } from 'file-saver';// import { exportJsonToExcel } from '@/vendors/Export2Excel.js';// import { writeFile } from 'fs-extra';export default {name: 'Index',props: ['title', 'treeData'],setup(props) {const data = reactive({treeData: props.treeData,});function exportTXT(dataRef) {let arrayChildren = [];arrayChildren.push(dataRef);let dimenData = flatten(arrayChildren);let fileData = [];dimenData.map((item) => {fileData.push(item.title);});const fileName = '导出文件.txt';const csvContent = fileData.map((row) => `${row}`).join('\n');const blob = new Blob([csvContent], { type: 'text/csv' });const url = URL.createObjectURL(blob);const link = document.createElement('a');link.href = url;link.download = fileName;document.body.appendChild(link);link.click();}function flatten(arr) {return [].concat(...arr.map((item) => [].concat(item, ...flatten(item.children))));}function handleSelect(val) {console.log('handleSelect', val);}function getRightMenuList(val) {console.log('getRightMenuList', val);}function exportPDF(val) {console.log('exportPDF', val);}function onContextMenuClick(treeKey, menuKey) {console.log(`treeKey: ${treeKey}, menuKey: ${menuKey}`);}return {...toRefs(data),getRightMenuList,handleSelect,exportTXT,exportPDF,onContextMenuClick,// exportToExcel,// flatten,};},};
</script><style scoped></style>