Home > Enterprise >  Nuxt: How to create links in a loop using the data as the link reference
Nuxt: How to create links in a loop using the data as the link reference

Time:01-24

I am reading a set of links from a data source (using $content) and would like to generate a list of HTML elements that will link to the respective page.

// test.yaml in content directory
links:
  - id: a
    title: A
  - id: b
    title: B
  - id: p
    title: P

Now, I would like to loop through this data and generate a set of HTML links

 // page.vue in pages directory
 //
 <template>
   <div v-for="link in this._links" :key="link.id">
      <NuxtLink to="/whatToPutHere">{{link.title}}</NuxtLink>
   </div>
 </template>

 // script
 <script>
   export default {
      async asyncData({ $content, params }) {
         const _links = await $content("test").fetch();
         return _links;
      }
   };
 </script>

For each of the items I would like a link such as:

  • For id a, the link should be /content/a
  • For id b, the link should be /content/b

Assume that the slug for the above links exist and the pages work as intended. Thanks

CodePudding user response:

you can use

<NuxtLink :to="`/content/${link.id}`">{{link.title}}</NuxtLink>

and it should work

In vue, you don't need to add the whole v-bind:tag and can just use :tag.
also if you v-bind any tag, whatever is in between quotations will be javascript code.

  •  Tags:  
  • Related