Activate Vue router/component by clicking next/previous event

I am currently using a vue-cli and router in my development project. I have multiple components and I need to find the best way to switch from one page to another when a user clicks on the next/previous button. Any suggestions would be greatly appreciated! 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 },
   ]

Answer №1

If you want to create your own App component, here's an example of how you could do it:

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

    // Set initial currentPageId based on URL
    this.setInitialPage(this.$router.currentRoute.fullPath)

    // Handle manual page changes
    this.$router.afterEach((to, from) => { this.setInitialPage(to.path) })
  },
  methods: {
    setInitialPage (currentPath) {
      this.currentPageId = this.pages.findIndex(page => page.path === currentPath)
    },
    next () {
      console.log('Moving to the next page')

      this.currentPageId++
      if (this.pages.length === this.currentPageId) {
        // Go back to the first page
        this.currentPageId = 0
      }

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

      this.currentPageId--
      if (this.currentPageId === -1) {
        // Go to the last page
        this.currentPageId += this.pages.length
      }

      this.$router.push(this.pages[this.currentPageId])
    }
  }
}

This component will navigate through the routes defined in the router/index.js file and can handle manual navigation as well, such as using router-link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The span's onclick function seems to be malfunctioning

I am encountering an issue where the Onclick event is not triggering on a specific tag. Strangely, the same onclick event works perfectly fine when bound to an image element. I am currently developing a follow and unfollow feature using PHP and jQuery. How ...

The select menu default value is not displaying properly after the update to select2 version 4.0.3

After updating the select2 package from version v4.0.0 to v4.0.4, I noticed that the default value of the select menu was no longer appearing as expected: https://i.sstatic.net/UO3yZ.jpg For those interested, here is a link to my code on JSBin: view jsbi ...

Guide to incorporating an input field within a select option in ant design and react

I have utilized Ant Design to create a select option, but now I am looking to implement an editable cell within the select option. Below is the code for my select option: <Select showSearch style={{ width: 400 }} placeholder="Select a Bank" op ...

Continuous Advancement Meter

I have implemented a progress bar, but I am encountering some issues with it. The progress bar is supposed to complete in 5 seconds. However, the value updates every second rather than continuously, causing it to pause intermittently. DEMO HTML <dx-p ...

The error message "THREE is not defined" indicates a problem

Hey there! I've been experimenting with running some three.js examples on my local machine. I ran into some security issues, so I set up a local server using Python. While the background image and text appear as expected, the animations are not workin ...

How to create an array of objects in TypeScript

I am looking to define an array of objects in TypeScript. Here is my example: const a = [{ name: 1, age: 2, car1: 8, car2: 8, car3: 8, name4: 1, age4: 2, car41: 8, car42: 8, car34: 8, }, { name: 1, age: 2, car1: 8, car2: 8, ...

Incorporate a dynamic animation feature into the Morris Chart

I have successfully created a chart using Morris JS. However, the chart currently loads on the screen without any animation effect. I am interested in enhancing the visual appeal of the chart by adding an animation effect to it. Below is the script I am u ...

Giving ng-click the current HTMLElement

Can the HTMLElement be passed to an ng-click function set up on a controller? Take a look at this example code: <div ng-controller="Controller"> <ul ng-repeat="item in items"> <li ng-click="handleThisElement($element)" id="{{item. ...

Is there a way to modify a document without altering its original location?

I attempted to load an entire page using ajax, with the doctype and html tags removed. However, when I tried setting it with the following code: document.documentElement.innerHTML=xmlhttp.responseText; Google Chrome returned an error message: An invalid ...

What is the best way to retrieve error messages from a transaction with ethers.js?

Incorporating a custom error in my Solidity contract: error Documents__AlreadyExist(string hash); The modifier I utilize is as follows: modifier alreadyExist(string memory hash) { if (s_documentsHashes[hash]) { revert Documents__AlreadyExi ...

Tips for updating the server without having to reload the page using vuejs

I am currently developing a CRUD application using vue-cli and Node.js on the server side. Here is a snippet of the form I have created: <template> <div id="formRoot"> <div class="form" > <form @submit.prevent="sendToTable ...

Change the behavior of JavaScript so that it executes when clicked, not when the

This script is currently set to run when the page loads: <script language="JavaScript"> j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); </script> Is there a way I can mak ...

Discontinuing the fieldset tab interface feature from a Dexterity content type

I am looking to modify a condition to prevent the loading of certain javascript code when inserting an object of my content type. The current condition works only when editing the object: <?xml version="1.0"?> <object name="portal_javascripts"> ...

Utilizing AJAX to load a WAV file

One of the tasks I'm working on involves a collection of audio files. When a file from this list is clicked, I want JavaScript to load and display the waveform of that specific audio file. The following function is responsible for drawing the wavefor ...

Nested Add and Remove using Jquery

I'm looking for assistance with implementing add/remove functionality for both top-level and sublists, which should result in a serialized output. Can anyone provide guidance on how to achieve this? For example: Add Question Question 1 | Delete An ...

What is the best way to pass a value to a modal and access it within the modal's component in Angular 8?

How can I trigger the quickViewModal to open and send an ID to be read in the modal component? Seeking assistance from anyone who can help. Below is the HTML code where the modal is being called: <div class="icon swipe-to-top" data-toggle="modal" da ...

Is there a way to disable text selection in AngularJS when double-clicking using ng-dblclick?

My element has ng-dblclick='doSomthing()' functionality that is functioning correctly, however, it also selects the text in the element which is not visually appealing. Is there a way to avoid this issue? ...

Implement a T3 App Redirect in a TRPC middleware for unsigned users

Is there a way to implement a server-side redirect if a user who is signed in has not finished filling out their profile page? const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCE ...

Access Mixins Throughout Your Entire Vue 3 Application

I'm a beginner with vue and I'm currently exploring the use of Websockets for my project. I want to make my websocket-plugin accessible from every component in my app, so I thought about using 'provide' and 'inject'? In my ma ...

Get to a certain nested div by using jQuery

Can someone assist me in accessing a specific element within a div while using a foreach loop? Below is the code snippet: HTML <div class="row menu-filter-items"> <div class="col-md-4 margin-b-30 menu-item"> <a href="#" class= ...