为什么写
? ? ? ? 来自抖音博主演示,vscode可以在网页端选择文件夹,觉得很新颖的功能。
目的
? ? ? ? 学会使用对应的API
完整代码
1.读取文件 showDirectoryPicker
async function pickDirectory() {
try {
const directoryHandle = await window.showDirectoryPicker({
id: 'test',
mode: 'readwrite',
startIn: 'documents',
});
// Construct and display the directory tree
const tree = await buildTree(directoryHandle);
nodes.value = [tree];
} catch (err) {
console.error("Error picking directory:", err);
}
}
async function buildTree(directoryHandle) {
const tree = {
key: guid(),
label: directoryHandle.name,
type: "directory",
children: [],
};
const dirEntries = await directoryHandle.values();
for await (const entry of dirEntries) {
console.log("🚀 ~ file: index.vue:98 ~ forawait ~ entry:", entry)
entry.isDirectory = entry.kind === "directory";
if (entry.isDirectory) {
const subtree = await buildTree(entry);
tree.children.push(subtree);
} else {
tree.children.push({ key: guid(), label: entry.name, type: "file", data: entry });
}
}
return tree;
}
注意点
????????1.读取属于iO操作,所以异步
????????2.文件夹属于树结构
2.高亮代码
? ? ? ? 使用【simple-syntax-highlighter】库
<template>
<ssh-pre
:label="options.label"
:language="options.language"
:dark="options.dark"
:editable="options.editable"
:tab="options.tab"
:copy-button="options.copyButton"
@copied="onCopiedDoSomething"
>
{{ code }}
</ssh-pre>
</template>
<script setup lang="ts">
import SshPre from "simple-syntax-highlighter";
import "simple-syntax-highlighter/dist/sshpre.css";
import { ref, reactive, watch } from "vue";
import Toast from "primevue/toast";
import { useToast } from "primevue/usetoast";
const toast = useToast();
const options = reactive({
language: "js",
label: "Javascript",
dark: true,
copyButton: true,
editable: true,
tab: " ",
});
const props = defineProps({
code: ""
});
const onCopiedDoSomething = () => {
console.log("copied");
toast.add({
severity: "success",
summary: "",
detail: "Copy success",
life: 3000,
});
};
</script>
<style lang="css" scoped></style>
? ? ? ?
3.总结
获取到文件,使用store存起来,使用高亮的js库展示
github链接
???????GitHub - Raywh/vue-directory: open directory for edit by browser