vue-前端读取文件夹并高亮代码
2023-12-25 19:44:45
为什么写
? ? ? ? 来自抖音博主演示,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
文章来源:https://blog.csdn.net/wanghu20150107010129/article/details/135205022
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!