【问题标题】:How to show only directory using `v-treeview` in vuetify?如何在 vuetify 中使用“v-treeview”仅显示目录?
【发布时间】:2020-11-10 08:10:06
【问题描述】:

我正在尝试使用v-treeview 显示唯一的目录/文件夹。响应对象以父子组合的形式出现

  • 如果父文件夹是文件夹,则类型为directory
  • 如果子文件是文件,则类型为file

下面是我的代码:

<v-treeview v-model="tree" :items="fileStructure" activable item-key="path" :open="open" :filter="filter" :search="search" open-on-click>
          <template v-slot:prepend="{ item, open }">
            <v-icon v-if="item.type == 'directory'" color="blue-grey darken-1">
              {{ open ? 'mdi-folder-open' : 'mdi-folder' }}
            </v-icon>
          </template>
          <template v-if="item.type == 'directory'" slot="label" slot-scope="{ item }">
            <a @click="showSelectedSubFolders(item)" v-if="item.type == 'directory'">{{ item.name }}</a>
          </template>
</v-treeview>

现在,使用上面的代码文件没有显示在文件夹下,但是当点击文件夹时它会创建一个空白空间。

我想要的行为是 - 它应该只显示文件夹。如果任何文件夹有子文件夹,则显示打开图标以打开子文件夹,否则不需要。如果任何文件夹/子文件夹只有文件,则无需显示打开图标。

【问题讨论】:

    标签: vue.js vuejs2 vuetify.js


    【解决方案1】:

    由于您只想显示文件夹,我建议使用计算属性过滤 fileStructure:

    computed: {
      filteredItems() {
        const temp = JSON.parse(JSON.stringify(this.fileStructure))
        
        function f(item) {
          if(item.children) {
            item.children = item.children.filter(f)
          }
          return item.type === "directory"
        }
    
        return temp.filter(f)
      }
    }
    

    这创建了fileStructure 的深层副本,因此我们不会更改原始数组。然后针对类型目录递归过滤项目。
    这样我们就可以去掉html中的ifs,只需要检查一个item是否有children。

    <v-treeview v-model="tree" :items="filteredItems" activable item-key="path" :open="open" :filter="filter" :search="search" open-on-click>
      <template v-slot:prepend="{ item, open }">
        <v-icon v-if="item.children && item.children.length > 0" color="blue-grey darken-1">
          {{ open ? 'mdi-folder-open' : 'mdi-folder' }}
        </v-icon>
      </template>
      <template slot="label" slot-scope="{ item }">
        <a @click="showSelectedSubFolders(item)">{{ item.name }}</a>
      </template>
    </v-treeview>
    

    【讨论】:

    • 我喜欢这个主意。我必须在右侧显示所选文件夹下的所有文件。你知道我为什么可以这样做吗? @杰伊冰箱
    • 既然这个答案解决了你的问题,我建议你接受它,然后就你的新问题提出另一个问题。
    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 2019-07-10
    • 2019-11-24
    • 2020-06-22
    • 1970-01-01
    • 2021-12-03
    • 2020-12-29
    • 1970-01-01
    相关资源
    最近更新 更多