Unable to switch between screens. VueJS

I am in the process of creating a dynamic gallery where users can view and navigate through different images. Currently, I have successfully set up the functionality to display images upon user interaction.

However, I have encountered an issue while trying to navigate between images within the gallery. When attempting to move forward to the next image, nothing happens. Strangely, clicking the previous button unexpectedly returns me back to the main gallery page.

Here are the defined routes for my application:

  const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue')
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/gallery',
    name: 'Gallery',
    component: () => import(/* webpackChunkName: "gallery" */ '../views/Gallery.vue')
  },
  {
    path: '/gallery/photo/:img',
    name: 'Photo',
    component: () => import(/* webpackChunkName: "photo" */ '../views/Photo.vue')
  }
]

In the Photo component, which displays the selected image, the following code is implemented:

    <template>
  <div>
    <img v-bind:src="img" alt="image" />
    <br />
    <button @click="previous()">Previous</button>
    <button @click="next()" style="margin-left: 10px">Next</button>
  </div>
</template>

<script>
export default {
  name: "Photo",

  computed: {
    img: function () {
      const url = this.$route.params.img;

      return url.replaceAll("%2F", "/").replaceAll("%3F", "?");
    },
  },

  methods: {
    previous: function () {
      this.$router.go(-1);
    },

    next: function () {
      this.$router.go(1);
    },
  },
};
</script>

The Photos component showcases all available images within the gallery, allowing users to select one as follows:

<template>
  <div id="gallery">
    <div id="photo" v-for="(img, index) in photos" alt="img" :key="index">
      <img v-bind:src="img" /><br />
      <router-link :to="{ name: 'Photo', params: { img: img } }">
        <button>Visit</button>
      </router-link>
    </div>
  </div>
</template>

<script>
export default {
  name: "Photos",

  data() {
    return {
      photos: [
        "https://images.unsplash.com/photo-1517694712202-14dd9538aa97?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80",
        "https://images.unsplash.com/photo-1590608897129-79da98d15969?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80",
        "https://images.unsplash.com/photo-1457305237443-44c3d5a30b89?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1053&q=80",
        "https://images.unsplash.com/photo-1571171637578-41bc2dd41cd2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80",
        "https://images.unsplash.com/photo-1534972195531-d756b9bfa9f2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjE3MzYxfQ&auto=format&fit=crop&w=1050&q=80",
      ],
    };
  },
};
</script>

EDIT

Despite setting up navigation methods for moving between images, the functionality does not seem to be working correctly:

https://i.sstatic.net/zSOwV.png

https://i.sstatic.net/DtRJ4.png

Answer №1

Your interpretation of the router.go function from the Vue.js documentation is incorrect - it is actually meant to navigate through history, explaining why you are directed back to the gallery on previous actions and unable to proceed forward.

My recommendation would be to have:

  • An array containing your image URLs
  • The index of the currently displayed image

If the current index is greater than zero, a previous button should be displayed linking to imageUrls[currentImageIndex- 1]. Similarly, if the index is less than imagesUrls.length - 1, a next button linked to imageUrls[currentImageIndex+ 1] should be shown.

Edit: Utilize <router-link> using these URLs instead of @click.

Tip: Ensure to update the currentImageIndex when adding or removing images.

(2nd Tip: Personally, I prefer using vuex and storing both the array and the current image index in the vuex store)

Answer №2

Revise the sections below:

<button @click="previous()">Anterior</button>
<button @click="next()" style="margin-left: 10px">Siguiente</button>

with

<button @click="previous">Anterior</button>
<button @click="next" style="margin-left: 10px">Siguiente</button>

Delete the parentheses after the function names.

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

Using router-links with events: A simple guide

My current issue involves passing information to another page. During testing without using routes, I was successful in passing information from one component to another. However, after implementing routes, clicking the event navigates to the other compo ...

The header and sub-navigation are in disarray and require some help

Dear web experts, After six months of learning to code websites, I'm tackling a big project with some challenges. The recent changes to the header and subnav have thrown everything off balance, making it look wonky and not quite right. Specifically, ...

Is there a way to automatically redirect the main html page to a different html page upon logging in?

I have created a main page in HTML with a login box that displays a message saying "Login successful" or "Login failed" based on whether the password entered is 8 characters or more. The validation function for this works correctly, but after successfully ...

How can we avoid 404 errors on page refresh in a Vue.js single-page application?

I'm encountering an issue with my single-page Vue app running at my_domain.com/my_app/. Whenever I refresh the page, I keep getting a 404 not found error (this is happening in the live environment, not during local development). I have followed the do ...

Failing to retrieve the file instance upon completing the upload process to cloudinary using nestjs

I am attempting to retrieve the secure file URL provided by Cloudinary after successfully uploading the asset to their servers. Although I can upload the file to Cloudinary, when I try to view the response using console.log(res), I unfortunately receive &a ...

Nuxt2 is not compatible with the current Long-Term Support version of Node (v18)

As a newcomer, I am embarking on my first Vue.js project with Nuxt. After executing "npm run dev" in the command prompt and running "npm install" for my project, I encountered the following: * Client ██████████████████ ...

issue with web worker not sending data to react component

I have incorporated the audio-recorder-polyfill into my React project to enable audio recording for Safari. While the recording seems to initiate successfully, there is an issue with the availability of audio data. The "dataavailable" event does not trig ...

How can I collapse the dropdown menu in typeahead.js?

I am currently utilizing typeahead.js for a typeahead functionality. My goal is to achieve the opposite of what was discussed in this thread: Programmatically triggering typeahead.js result display Despite attempting to trigger a blur event on the typeah ...

What is the best way to set the state to false upon unmounting a component in react?

Currently, I am controlling the state of a dialog using context. Initially, the isOpen state is set to false. When the add button is clicked, the state isOpen becomes true and clicking the cancel button will revert it back to false. If the user does not c ...

Is it possible to store a randomly generated variable in JavaScript for future reference?

Currently, I am involved in a project that involves generating random variables to create unique scenes. One specific variable is the location of these scenes. My goal is to be able to generate a location with just one button click. Subsequently, by pressi ...

Insert item at the end of the box and move all elements upwards

Hello! I'm experimenting with creating something using javascript's createElement method. My goal is to achieve an effect similar to this image: https://i.stack.imgur.com/itKUK.gif Currently, my code is functional, but the animation goes from to ...

Error in Node.js: Cannot listen on socket.io object as it does not have a 'listen' method

I am currently developing a Node application using socket.io version 0.9.13 alongside Express 3.0.6. I am encountering an issue where the app fails to run due to an error stating that socket.io does not have a method called listen(). Here is the code snipp ...

The 3D formula for calculating the distance between a point and a line

Can anyone provide me with a computer program or algorithm that calculates the distance between a point and a line in a three-dimensional space? The program can be written in JavaScript or any other programming language. In this scenario, P represents th ...

disableDefault not functioning properly post-fadeout, subsequent loading, and fade-in of new content with a different URL into

After extensive searching, I still haven't found a solution to my problem. My task involves bringing in HTML pages into a div element. I managed to make the content fade out, load new href content, and then fade in the new content. However, I'm ...

I aim to retrieve the names of all directories

I am seeking assistance from seniors in creating a dropdown list of root directories using PHP. I have almost completed the task, but I am facing an issue with not being able to retrieve the root directory. For example, I want all directories like home/ab ...

The output stored in the variable is not appearing as expected

https://i.sstatic.net/VWCnC.pnghttps://i.sstatic.net/UoerX.pnghttps://i.sstatic.net/n52Oy.png When retrieving an API response and saving it in the "clima" variable, it appears as undefined. However, when using console log, the response.data is visible ...

Guide on adjusting the value for a Bootstrap slider

Using the bootstrap slider, I am trying to configure a way to assign a value to the handle from another variable. Although I came across a method that uses the data-slider-value attribute for this purpose, it did not work for me. <input id="gravite" na ...

Exploring the World of 3D Design with Three

Is there anyone out there who can assist me with three.js? I am in need of drawing a background, something like a THREE.Sprite, but it needs to be positioned UNDER any 3D object that will be drawn later. I have a camera that can only move along the Z axis ...

The trio of Javascript, Ajax, and FormData are

I'm struggling with sending form values to a PHP file. Here's the code I have: <form role="form" id="upload_form" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="formlabel">Title< ...

Experiencing difficulties launching my Server.JS due to a listening error

Hey there, I'm struggling to get my server.js up and running. Whenever I try to run node on it, I keep getting the error message "listening on *:3000". Below is the code for my server.js: var app = require('express')(); var http = require(&a ...