Search code examples
vue.jsvue-routervuejs3vue-router4

Creating a next page button on Vuejs 3 with vue-router


I want to add a button on my page such that it links to the next page and prev page of the router links. My router setup is as:

          <li class="nav-item">
            <router-link :to="{ name: 'testa' }">TestA</router-link>
          </li>
          <li class="nav-item">
            <router-link :to="{ name: 'testb' }">Testb</router-link>
          </li>

I want to make something like this:

<button @click="nextPage()> 
<button @click="PrevPage()> 

Which would go to the next page (testb) in this case and a prev button which would go to the prev page if it exists.

My router's index.js looks like this

import { createRouter, createWebHistory } from 'vue-router'
const routes = [
  {
    path: '/home',
    name: 'testa',
    component: () => import('../views/home.vue')
  },
  {
    path: '/contact',
    name: 'testb',
    component: () => import('../views/contact.vue')
  },
  {
    path: '/testimonials',
    name: 'testc',
    component: () => import('../views/testimonials.vue')
  },
  

How do i proceed?


Solution

  • You can add meta info to the routes, which is nice since all navigation info is in one place.

    import { createRouter, createWebHistory } from 'vue-router'
    const routes = [
      {
        path: '/home',
        name: 'testa',
        component: () => import('../views/home.vue'),
        meta: {
          next: 'testb',
          prev: 'testc'
        }
      },
    

    Then in the button methods

    methods:{
      prevPage(){
         this.$router.push({ name: this.$router.currentRoute.value.meta.prev})
      },
      nextPage(){
         this.$router.push({ name: this.$router.currentRoute.value.meta.next })
      }