EricTalv
EricTalv

Reputation: 1049

How to read specific directory for files in vue

I am trying to create a simple project display page, where you have a Project List page which displays all posts from a Projects_List Directory,

heres and example of what i'm trying to recreate.

this is my folder structure:

project
|-- .vuepress
|-- projectslist
|   |-- post1
|   `-- post2
|-- About.md
|-- ProjectsList.md
`-- theme
    `-- layouts
        |-- ProjectsList.vue
        `-- About.vue

We are working in the ProjectsList.vue

I was looking through the site with VueDev tools and found that vuepress sends along this data: $site.pages, which is an object an array of 4, which includes all of my .md files.

Now when i run this code:

    <ol>        
       <li v-for="page in $site.pages"> 
                {{ page.relativePath }}
       </li>
   </ol>

page.relativePath is <pagename>.md

I get this output on my page:

 1. About.md
 2. ProjectsList.md
 3. projectslist/post1.md
 4. projectslist/post2.md

So basically the $site.pages reads all pages from root level, theres also $localePath and $site.base which are both equal to /.

So what I am thinking is, if i can change $site.base to /projectslist it should only read the .md files from that folder.

heres where my vue knowledge falls short, I cant seem to change those parameters, I tried catching them in the computed & data but then i get an error that they are not defined.

Upvotes: 1

Views: 2720

Answers (2)

EricTalv
EricTalv

Reputation: 1049

Though @Delen Malan's post solves my issue, I found out that using v-for and v-if on the same element isn't a good practice

here's a more indepth explanation

So instead with a little tweaking with the Computed method I eventually crafted this:

        <li v-for="item in projectsList">
            <a href="#">
                {{ item.title }}
            </a>
        </li>

<script>
    export default {   
        computed: {
            projectsList() {                
                return this.$site.pages.filter(page => page.path.includes('projectslist/'));
            }   
        }
    }
</script>

We also get the following benefits:

The filtered list will only be re-evaluated if there are relevant changes to the projects array, making filtering much more efficient. Using v-for="item in projectsList", we only iterate over active projects during render, making rendering much more efficient.

Logic is now decoupled from the presentation layer, making maintenance (change/extension of logic) much easier.

Upvotes: 1

D Malan
D Malan

Reputation: 11414

A page object should also contain a path value. You can filter $site.pages for paths contain projectslist/.

    <ol>        
       <li v-for="page in $site.pages">
            <span v-if="page.path.includes('projectslist/')">
                {{ page.relativePath }}
            </span>
       </li>
   </ol>

Upvotes: 2

Related Questions