klren0312 / daliy_knowledge

知识积累,正确使用方式是watch
22 stars 4 forks source link

js选择文件夹 获取文件夹树 #812

Open klren0312 opened 4 months ago

klren0312 commented 4 months ago

1709191711239


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./index.css">
</head>
<body>
  <div id="app">
    <el-button @click="openFolder">选择文件夹</el-button>
    <div style="width: 100vw;display: flex;">
      <el-tree
        style="width: 50%"
        :data="fileTree"
        :props="{
          label: 'name',
          children: 'children'
        }"
      >
      </el-tree>
    </div>

  </div>
  <script src="./vue.min.js"></script>
  <script src="./elementui.js"></script>
  <script>

    new Vue({
      el: '#app',
      data () {
        return {
          fileTree: {},
          fileObj: {},
        }
      },
      methods: {
        async openFolder() {
          const dirHandle = await window.showDirectoryPicker()
          const root = await this.processDir(dirHandle, null)
          this.fileTree = root.children
        },
        async processDir(dirHandle) {
          const fileTree = { name: dirHandle.name, isDir: true, handle: null, children: [] }
          for await (const entry of dirHandle.values()) {
            if (entry.kind === 'directory') {
              const subtree = await this.processDir(entry)
              fileTree.children.push(subtree)
            } else if (entry.kind === 'file') {
              fileTree.children.push({ name: entry.name, isDir: false, handle: entry })
            }
          }
          return fileTree
        },
      }
    })
  </script>
</body>
</html>