skip to Main Content

Im a novice in NuxtJS. My page is structured with a navbar/menu, blog page with all articles listed and a couple of mostly static pages.(like most company websites)

I am retrieving my data from a Strapi API, where I can only fetch single entries by their ID.

What I have to do:

When the user clicks on the navbar link, I need to pass the ID of the corresponding article/post to the article component in order to retrieve the article from the API. So far it is working quite well, but doing it via router params, an article will have an URL like https://www.example.com/posts/63ndjk736rmndhjsnk736r

What I would like to do:

I would like to have an URL with a slug https://www.example.com/posts/my-first-Post and still pass the ID to the article component/page.

Whats the best way to do that?

2

Answers


  1. You can use like _slug.vue in pages folder.

    and your routes like this;

    {
      name: 'posts-slug',
      path: '/posts/:slug?',
      component: 'pages/posts/_slug.vue'
    }
    

    then create a new vue file.

    export default {
      validate ({ params }) {
        return /^d+$/.test(params.id)
      }
    }
    

    this way you can also access the parameter

    Login or Signup to reply.
  2. You can use query. Here is some example:

    I have some data:

    data = [{id: "63ndjk736rmndhjsnk736r", name: "my-first-post"}, {id: "88ndjk736rmndhjsnk736r", name: "my-second-post"}]
    

    In my navbar list:

    <template v-for="(item, index) in data" key="index">
        <router-link :to="{ path: '/posts/' + item.name, query: { id: 'item.id' }}"
        >{{item.name}}</router-link>
    </template>
    

    How your routes show:

    http://example.com/posts/my-first-post?id=63ndjk736rmndhjsnk736r
    

    What you need:

    1. Create dynamic Route -> https://nuxtjs.org/guide/routing/#dynamic-routes
    2. Pass query named id which is your single entry ID
    3. Get query (id) and fetch your single entry using query id:
      const postId = this.$route.query.id
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search