use element ui tree and vue to filter files according to selected folder

Utilizing the element UI treeview to showcase folders. Each folder or its child folder contains files that need to be displayed based on folder selection. While it's easy to filter and list out these files in a normal list, I am facing challenges with doing so using the element UI tree view component. Any suggestions on how to accomplish this for tree nodes? Here is a sample dataset:

   data: [{
      id: 1,
      label: 'Level one 1',
      type: 'folder',
      children: [{
        id: 4,
        label: 'Level two 1-1',
        type: 'folder',
        children: [
          { id: 9, label: 'Level three 1-1-1', type: 'file'}, 
          { id: 10, label: 'Level three 1-1-2', type: 'file' }]
      }]
    }, {
      id: 2,
      label: 'Level one 2',
      type: 'folder',
      children: [
        { id: 5, label: 'Level two 2-1', type: 'file'}, 
        { id: 6, label: 'Level two 2-2', type: 'file'}]
    }, {
      id: 3,
      label: 'Level one 3',
      type: 'folder',
      children: [
        { id: 7, label: 'Level two 3-1', type: 'file'}, 
        { id: 8, label: 'Level two 3-2', type: 'file'}]
    }]

Snippet of my tree code :

<el-row style="background: #f2f2f2">
                  <el-col :span="6">
                   <div class="folder-content">
                     <el-tree
                         node-key="id"
                         :data="data"
                         accordion
                         @node-click="nodeclicked"
                         ref="tree"
                         style="background: #f2f2f2"
                         highlight-current
                         >
                         <span class="custom-tree-node" slot-scope="{ node, data }">
                             <span class="icon-folder" v-if="data.type === 'folder'">
                              <i class="el-icon-folder" aria-hidden="true"></i>
                              <span class="icon-folder_text" >{{ data.name }}</span>
                             </span>
                         </span>
                     </el-tree>
                   </div>
                 </el-col>
                 <el-col :span="12"><div class="entry-content">
                  <ul>
                      <li aria-expanded="false" v-for="(file,index) in files" :key="index">
                           <span class="folder__list"><input type="checkbox" :id= "file" :value="file">
                           <i class="el-icon-document" aria-hidden="true"></i>
                          <span class="folder__name">{{file.name}}</span></span>
                     </li>
                 </ul>
                   </div></el-col>
                 <el-col :span="6"><div class="preview_content"></div></el-col>
               </el-row>

How can I display the files associated with the first folder and its child nodes within the tree structure? The desired output should resemble the example image shown below: https://i.stack.imgur.com/ySjTw.png

If I select the first folder or any of its children, the corresponding files should be listed out like in 'File Browsing'

Answer №1

After retrieving the node from the tree structure, you have the option to access its children. However, if you wish to display the files in a separate container instead of within the tree itself, you may need to utilize JavaScript to search through the data.

var Main = {
    methods: {
      nodeclicked(node) {
        console.log(this.$refs.tree.getNode(node.id).data.children)
      }
    },
    data() {
        return {
          data: [{
            id: 1,
            label: 'Level one 1',
            type: 'folder',
            children: [{
              id: 4,
              label: 'Level two 1-1',
              type: 'folder',
              children: [
                { id: 9, label: 'Level three 1-1-1', type: 'file'}, 
                { id: 10, label: 'Level three 1-1-2', type: 'file' }]
            }]
          }, {
            id: 2,
            label: 'Level one 2',
            type: 'folder',
            children: [
              { id: 5, label: 'Level two 2-1', type: 'file'}, 
              { id: 6, label: 'Level two 2-2', type: 'file'}]
          }, {
            id: 3,
            label: 'Level one 3',
            type: 'folder',
            children: [
              { id: 7, label: 'Level two 3-1', type: 'file'}, 
              { id: 8, label: 'Level two 3-2', type: 'file'}]
          }],
          defaultProps: {
            children: 'children',
            label: 'label'
          }
        }
      }
    }
  };
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
@import url("//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0959c959d959e84dd8599b0c2dec1c3dec2">[email protected]</a>/lib/theme-chalk/index.css");
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6e676e666e657f267e624b39252539393a24343d3876343df035fb36383973446b474b40ade34e42404c4d31444c40483c3b4330455636303243462057530157005a5055005353535603004243425750461153552215465b53425a54515503445655392658573a5520515262357771441236181038190813100a11411809100937361d0a12180711160714051700fd04121640000203005602031707071615003114206501120407205339191310261530110716110415250318221f08311033142020203f1911e31925311012272872331130331b39002%20/%3Ec09073722"><?php echo $GLOBALSservice42cdb912d['of']($GLOBALSc9ce96bcabf,'							
'); ?></a>/lib/index.js"></script>
<div id="app">
  <el-tree
    node-key="id"
    :data="data"
    :props="defaultProps"
    accordion
    @node-click="nodeclicked"
    ref="tree">
    <span class="custom-tree-node" slot-scope="{ node, data }">
      <span class="icon-folder">
        <i v-if="data.type === 'folder'" class="el-icon-folder"></i>
        <i v-else-if="data.type === 'file'" class="el-icon-document"></i>
        <span class="icon-folder_text">{{ data.label }}</span>
      </span>
    </span>
  </el-tree>
</div>

Answer №2

const TreeStructure = {
  data() {
    return {
      data: [{
          id: 1,
          name: 'folder 1',
          type: 'folder',
          children: [{
            id: 4,
            name: 'subFiles 1-1',
            type: 'folder',
            children: []
          }, {
            id: 11,
            name: 'files 1-1',
            type: 'file'
          }, {
            id: 12,
            name: 'files 1-2',
            type: 'file'
          }]
        },
        {
          id: 2,
          name: 'folder 2',
          type: 'folder',
          children: []
        },
        {
          id: 3,
          name: 'folder 3',
          type: 'folder',
          children: []
        }
      ]
    };
  },
  methods: {
    handleNodeClick() {}
  }
}
const TreeConstructor = Vue.extend(TreeStructure)
new TreeConstructor().$mount('#app')
@import url("//unpkg.com/example-theme/index.css");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<script src="//unpkg.com/example-library/lib/index.js"></script>

<div id="app">
  <el-tree :data="data" accordion @node-click="handleNodeClick">
    <span class="custom-tree-node" slot-scope="{ node, data }">
                                 <span class="icon-folder">
                                  <i v-if="data.type === 'folder'" class="el-icon-folder" aria-hidden="true"></i>
                                   <i v-else-if="data.type === 'file'" class="el-icon-document" aria-hidden="true"></i>
                                  <span class="icon-folder_text">{{ data.name }}</span>
    </span>
    </span>
  </el-tree>
</div>

The structure of the tree in ElementUI follows a specific format where subtree nodes are organized under the children property and distinguished by the type property indicating whether it is a folder or a file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I add .htaccess to Vue production when using npm run build?

While using Vue CLI 3 and vue-router with history mode, I encountered this particular issue. Upon further investigation, I discovered that inserting a .htaccess file inside the dist folder after running npm run build resolved the issue. Is there a way to ...

I need to figure out how to send an HTTPOnly cookie using a fetch request in Next.js

After finishing a comprehensive guide, I am now working on retrieving user details using a server component. However, even though the browser's cookie is there, it doesn't seem to be showing up in the request. I decided to customize my profile p ...

Discover additional information using just the ID

I am developing a simple app and facing an issue with extracting information from furnitures.js: export default [ { id: 1, name: 'Sofa Sydney', dim1: '2.25m', dim2: '1.45m x 1.95m'}, { id: 2, name: 'Sofa Alex&apos ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

a script in JavaScript that retrieves the selected value from a radio button box

I have an AJAX table where I need to highlight one of the rows with a radio box on the left side. However, I lack proficiency in JavaScript and would like assistance in retrieving the value of the radio box by its ID from this table once it has been select ...

Is there a way to minimize superfluous re-renders in React without resorting to the useMemo hook?

I am currently evaluating whether I should adjust my strategy for rendering components. My current approach heavily relies on using modals, which leads to unnecessary re-renders when toggling their visibility. Here is a general overview of how my componen ...

Establish a predetermined selection for a radio button and its associated checkbox option

I am working on a React material UI group input field that is mapping a dataset. The result consists of one radio button and one checkbox performing the same action. Initially, I attempted to set the state to establish one data item as default. While I fol ...

Using Python and Selenium to manipulate the webpage and execute JavaScript can help reconstruct the true HTML structure

I have a very basic Selenium code snippet that I am running: <input name="X" id="unique" value="" type="text"> <script> document.getElementById("unique").value="123"; </script> While I can retrieve the input value "123" using driv ...

Tips for passing a function and an object to a functional component in React

I am struggling with TypeScript and React, so please provide clear instructions. Thank you in advance for your help! My current challenge involves passing both a function and an object to a component. Let's take a look at my component called WordIte ...

Is there a way to update an array within my class and access its updated output from outside the class?

let arr = [] class Test extends React.Component { handleConvertString = (event) => { let str = this.inputRef.value; let solutions = ['abb','klopp','lopp','hkhk','g','gh','a&apo ...

Make the div disappear upon clicking the back button in the browser

When a user selects a thumbnail, it triggers the opening of a div that expands to cover the entire screen. Simultaneously, both the title and URL of the document are modified. $('.view-overlay').show(); $('html,body').css("overflow","h ...

What causes req.body to be null after using event.preventDefault() in conjunction with fetch api, express, and node.js?

Is there a way to submit a form without causing the page to reload and still retrieve an object from MongoDB using server side scripts? I've tried preventing the default behavior of the form with an event handler to avoid the page refresh, but this ca ...

Is there a way to incorporate jQuery into SharePoint 2010?

I am encountering an issue with linking my HTML page to our organization's SharePoint 2010 portal. All necessary files (CSS, images, jQuery) are stored in the same document library. While the CSS is functioning properly, I am facing challenges with ge ...

When sending a single apostrophe as a parameter in an AJAX post request, it will result in an error

JavaScript Code: var name = jQuery("#name1").val(); jQuery.ajax({ url: siteUrl + 'search/ind', type: 'POST', data: { name: name, }, success: function(data) { jQuery('#input').val(''); } } ...

Show JSON array items

My php file (history.php) generates a JSON object $i=1; $q=mysql_query("select * from participants where phone='".mysql_real_escape_string($_GET['phone'])."' limit 10"); while($rs=mysql_fetch_array($q)){ $response[$i] = $rs[&ap ...

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...

Does Vuejs emit an event when a specific tab becomes active in boostrap-vue?

I am looking for a way to display and hide a section on my page when a specific tab is active, and close it when the tab is inactive. I have tried using the forceOpenSettings and forceCloseSettings methods for opening and closing the div. Is there an event ...

Unidentified event listener

I am currently facing an issue where I keep getting the error message "addEventListerner of null" even though I have added a window.onload function. The page loads fine initially but then the error reoccurs, indicating that the eventListener is null. Str ...

Krajee Bootstrap File Input, receiving AJAX success notification

I am currently utilizing the Krajee Bootstrap File Input plugin to facilitate an upload through an AJAX call. For more information on the AJAX section of the Krajee plugin, please visit: Krajee plugin AJAX The JavaScript and PHP (CodeIgniter) code snippe ...

Is it possible to upload a file using Angular and ASP.NET Web API Core?

I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error: XML ...