打开文件夹并获取文件

文章介绍了如何在Vue应用中使用`showDirectoryPicker`方法获取文件夹,通过`entries`遍历其内容,并利用`Highlight.js`插件实现代码高亮显示。展示了递归获取文件夹树状结构和异步处理文件内容的过程。
摘要由CSDN通过智能技术生成

直接贴代码,主要是调用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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值