直接贴代码,主要是调用showDirectoryPicker这个方法,返回文件夹,通过entries方法可以获取这个文件夹里面的内容,文件内容也可以看,只是没有结构和高亮,可以通过Highlight.js这个插件来实现
<template>
<div class="box">
<div class="left">
<div class="open_file" @click="openFile">打开文件夹</div>
<el-tree :data="menu" :props="defaultProps" @node-click="handleNodeClick" v-if="menu.length !== 0" />
</div>
<div class="right">
{{ contentHtml }}
</div>
</div>
</template>
<script setup lang='ts'>
import { ref } from 'vue'
let contentHtml = ref("");
let menu = ref([]);
const defaultProps = {
children: 'children',
label: 'name',
}
const handleNodeClick = (data: any) => {
console.log(data);
data.getFile().then(file => {
let reader = new FileReader();
reader.readAsText(file, 'utf-8');
reader.onload = (e) => {
contentHtml.value = e.target?.result
}
});
}
const openFile = async () => {
let handle = await showDirectoryPicker();
let root = await handleFile(handle);
menu.value = root.children;
}
// 递归获取整个文件夹的树状结构
const handleFile = async (handle: any) => {
if (handle.kind === "file") return handle; //如果是文件返回
handle.children = [];
let iter = handle.entries(); //获取文件夹里面的所有内容
for await (let iterValue of iter) { //异步遍历迭代器
let subHandle = await handleFile(iterValue[1])
handle.children.push(subHandle);
}
return handle;
}
</script>
<style scoped lang='scss'>
$height: 40px;
.box {
width: 1920px;
height: 1080px;
display: flex;
.left {
width: 300px;
height: 100%;
background-color: cadetblue;
padding-top: 20px;
.open_file {
width: 100px;
height: $height;
text-align: center;
line-height: $height;
background-color: blue;
margin: 0 auto;
color: #fff;
cursor: pointer;
}
}
.right {}
}
</style>