Milan Milosev
Milan Milosev

Reputation: 256

Trigger Vue router/component with next/previous click event

I'm using a vue-cli, router. and I have separate components. What will be the best way to change from one page to another on next/previous click event? Thank you!

   // App.vue
   <nav>
      <router-link to="/">Homepage</router-link>
      <router-link to="/link_1">About</router-link>
      <router-link to="/link_2">Portfolio</router-link>
      <router-link to="/link_3">Contact</router-link>
    </nav>

    <div @click="next">Go to next link</div>
    <div @click="preview">Go to previous link</div>

   // router/index.js
   const routes = [
     { path: '/', component: home },
     { path: '/link_1', component: About },
     { path: '/link_2', component: Portfolio },
     { path: '/link_3', component: Contact },
   ]

Upvotes: 0

Views: 1936

Answers (1)

Yann Bertrand
Yann Bertrand

Reputation: 3114

Here is how you could define you App component

export default {
  name: 'app',
  data () {
    return {
      routes: [],
      currentRouteId: 0
    }
  },
  mounted () {
    this.routes = this.$router.options.routes

    // Init currentRouteId from URL
    this.refreshCurrentRouteId(this.$router.currentRoute.fullPath)

    // Handle manual page change
    this.$router.afterEach((to, from) => { this.refreshCurrentRouteId(to.path) })
  },
  methods: {
    refreshCurrentRouteId (currentPath) {
      this.currentRouteId = this.routes.findIndex(route => route.path === currentPath)
    },
    next () {
      console.log('Going to next page')

      this.currentRouteId++
      if (this.routes.length === this.currentRouteId) {
        // Go back to first route
        this.currentRouteId = 0
      }

      this.$router.push(this.routes[this.currentRouteId])
    },
    preview () {
      console.log('Going to previous page')

      this.currentRouteId--
      if (this.currentRouteId === -1) {
        // Go to last route
        this.currentRouteId += this.routes.length
      }

      this.$router.push(this.routes[this.currentRouteId])
    }
  }
}

It'll navigate through routes defined inside the router/index.js file and handle manual navigation (using router-link or so).

Upvotes: 1

Related Questions