How to interpolate nuxt-link's `to` prop?

Viewed 1162

I've been searching this for a while but can't seem to get it right. I have a basic Nuxt project with the following directory structure (ignore the fun.vue) :

dir structure

The idea is to be able to navigate to a single post with paths like http://localhost:3000/posts/1

This works, if I manually go to .../posts/1 I get my page defined in _id.vue.

The problem is that, in my index page, I cannot get <NuxtLink> to go to single post pages. I have a basic v-for looping over my fetched posts array, like so:

<template>
  <div>
    <div v-for="post in posts" :key="post.id">
      {{ post.title }}
      <NuxtLink to="`posts/${post.id}`">Link to post</NuxtLink>
    </div>
  </div>
</template>

I would expect, upon clicking on the 2nd post's link for example, to navigate to posts/2, but instead I get /%60posts/$%7Bpost.id%7D%60. Why isn't the template string converted normally? I've also tried using a computed value with no success, and the Nuxt Routing docs haven't been of much help.

Highly appreciate any help regarding this.

3 Answers

You can use something like this the ":" in front of it will make it dynamic and you can use template literals in between those double quotes

<NuxtLink :to="`posts/${post.id}`">Link to post</NuxtLink>

I tried your code in my development environment. You also may forgot to add "/" in front of "posts":

<NuxtLink :to="`/posts/${post.id}`">Link to post</NuxtLink>

If you put your code without "/" in a Nuxt "layout", it adds "posts" iteratively to your "URL" and makes the destination wrong:

http://localhost:3000/posts/posts/2

This happens when you click on post 1 and after to post 2.

Related