Navigating through a series of items in VueJS can be easily accomplished by using a

Below is the Vue instance I have created:

new Vue({
    el: '#app',
    data: {
      showPerson: true,
      persons:
        [
          {id: 1, name: 'Alice'},
          {id: 2, name: 'Barbara'},
          {id: 3, name: 'Charlotte'}
        ],
    },
    methods: {
      nextPerson: function(){
        this.showPerson = false;
      }
    }
  });

I am aiming to iterate through the array of objects called persons. The list should begin with the first element and below it, there should be a button that toggles between hiding the current element and showing the next one in the array. Once the user reaches the last element, clicking the Next button should not cycle back to the first element.

Here is the corresponding HTML code:

<div id="app">
  <ul v-for="person in persons">
    <li v-if="showPerson">{{person.name}}</li>
  </ul>
  <button @click="nextPerson">Next Person</button>
</div>

You can also view the complete example on JSBin here. Currently, I can only toggle all items at once instead of one by one. How should I approach implementing this functionality?

Answer №1

To ensure smooth navigation between different persons being displayed on the screen, it is essential to maintain an index for the currently shown person. I have denoted this index using the variable currentPersonIndex.

When the user clicks on a button to view the next person, you should increment the index by 1 in the click event handler. It is crucial to check that the index remains within the bounds of the array length. Here's how I have updated the click event handler:

showNextPerson: function() {
  if(this.currentPersonIndex < (this.peopleList.length - 1)) {
    this.currentPersonIndex++;
  }
}

To display the details of the current person, you can either utilize a computed property or directly access the information using an inline expression like

this.peopleList[this.currentPersonIndex].name
.

I have implemented a conditional statement with

v-if="this.currentPersonIndex != this.peopleList.length - 1"
to hide the "next" button when the last element in the array is reached.

new Vue({
  el: '#app',
  data: {
    currentPersonIndex: 0,
    peopleList: [{
        id: 1,
        name: 'Alice'
      },
      {
        id: 2,
        name: 'Ben'
      },
      {
        id: 3,
        name: 'Charlie'
      }
    ],
  },
  methods: {
    showNextPerson: function() {
      if(this.currentPersonIndex < (this.peopleList.length - 1)) {
        this.currentPersonIndex++;
      }
    }
  },
  computed: {
    currentPersonDetails: function() {
      return this.peopleList[this.currentPersonIndex];
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.min.js"></script>
<div id="app">
  Displayed Person: {{ currentPersonDetails.name }}
  <button v-if="this.currentPersonIndex != this.peopleList.length - 1" @click="showNextPerson">Next Person</button>
</div>

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

Make sure to include additional details, such as copyright information and a link to read more, when copying text. It is also important to maintain the

When attempting to include a read more link in my copied text, I am encountering an issue where the line breaks and formatting are being neglected: <script type='text/javascript'> function addLink() { var body_element = document.getEl ...

Tips for adjusting the width of a Facebook embedded video within its container using ReactPlayer

Has anyone encountered issues with adding an embedded video to a NextJS app using ReactPlayer and Facebook videos? It seems that Facebook does not support the width="100%" attribute, as it always snaps back to 500px. Interestingly, this works wel ...

Django Implementation of JavaScript Confirmation Dialogue

Currently working on a Django form that requires a confirm/cancel dialog upon submission. I've considered sending POST data from jQuery, but I'm curious if it's possible to integrate a JavaScript dialog as middleware instead? ...

Delaying loops with JQuery Ajax

I am attempting to implement a delay in my AJAX data processing so that the loop runs a bit slower. Here's the code I'm working with: $(document).ready(function (){ $('#button').click(function(){ $('#hide').show ...

Animate the jQuery: Move the image up and down inside a smaller height container with hidden overflow

Check out the fiddle to see the animation in action! The image is programmed to ascend until its bottom aligns with the bottom of the div, and then descend until its top aligns with the top edge of its parent div, revealing the image in the process. ...

MooTools Request Unsuccessful

I'm encountering a problem with MooTools where every time I try to send a request, it fails. I'm having trouble figuring out the issue because when I attempt to retrieve the header info, the console just displays "Refused to get unsafe header &ap ...

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

jScrollPane malfunctioning with Bootstrap 3's dropdown menu

I'm attempting to add a vertical scrollbar to a Bootstrap dropdown. Below is the HTML code I'm working with: <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle btn_drop_down" data-toggle="dropdown"> ...

Jenkins encountered an issue where script execution was blocked on <URL> due to the document's frame being sandboxed without the 'allow-scripts' permission set

When using an iFrame in HTML, it's always best to remember to sandbox it and set the 'allow-scripts' permission to true. However, I'm facing an issue in my pure Angular JS application where there is no iFrame present. It runs smoothly ...

What method is the most effective for extracting the first line of a file in Node.js quickly?

If you are faced with multiple lengthy text files and your goal is to extract data solely from the first line of each file (without delving into the rest), how would you recommend achieving this efficiently using Node.js? Appreciate any suggestions! ...

Toggle jQuery to hide a div and update its CSS styling

There is an anchor with the class of "hide-btn1" that I want to trigger a series of actions when clicked: The rcol-content should hide and the text should change from Hide to Show The #container width needs to increase to 2038px The table.status-table wi ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...

Exploring through a dynamically generated table containing JSON data

I have successfully implemented a dynamic HTML table that is populated with JSON data based on the value of a variable when the "go" button is clicked. The initial population and search functionality work flawlessly. However, I encountered an issue when ch ...

What is the recommended approach for embedding scripts within Angular templates?

I am working on an Angular SPA that consists of multiple tabs, each served by templates. Depending on the tab, different scripts (both local and CDN) are required. Therefore, I am looking for a way to load these scripts only when they are needed, which mea ...

The issue of calling the store() function on null in Laravel with Nuxt

I'm encountering an issue with saving data in Laravel from my Nuxt Application. I successfully created data using Postman, but for some reason it's not working here. Controller $book = Book::create([ 'name' => $request ...

performing a jQuery AJAX call from a UIWebView during the initial launch of the app following installation

We have a uiWebview that uses jquery for an ajax request to log in. It functions flawlessly on mobile safari and all browsers. However, when the application is launched for the first time after installation, the ajax request seems to be sent out but no re ...

Modifying text dynamically in AngularJS by cycling through an array of strings

Is it possible to create a text carousel in my angular controller without using an infinite loop? For example: //html <span> {{ notes }}</span> //angular controller var i = 0; var array = ["A", "B", "C", "D", "E"]; while (true ...

Is it possible to notify the user directly from the route or middleware?

In my current setup, I am utilizing a route to verify the validity of a token. If the token is invalid, I redirect the user to the login page. I am considering two options for notifying users when they are being logged out: either through an alert message ...

Unfortunately, my deployment on Vercel encountered an error related to npm. Specifically, the error involved the extraction of a file from the tarball for node-v18.15

Trying to deploy my GitHub project on Vercel. The project is built using Vue. However, when building the project on Vercel, I encountered numerous errors like this: npm ERR! gyp verb extracted file from tarball node-v18.15.0/include/node/openssl/archs/VC-W ...

Exploring the FunctionDirective in Vue3

In Vue3 Type Declaration, there is a definition for the Directive, which looks like this: export declare type Directive<T = any, V = any> = ObjectDirective<T, V> | FunctionDirective<T, V>; Most people are familiar with the ObjectDirectiv ...