Develop a carousel component using Vue.js

I'm currently working on a dashboard that needs to display cards, but I'm running into an issue. I want only four cards visible at a time, and when you click the arrow, it should move just one step to the next card. For example, if cards 1-4 are showing, clicking the right arrow should reveal cards 2-5. However, my current setup jumps straight from 1-4 to 5-10 when the right arrow is clicked.

Here's what I have so far:

computed: {
    cardsToDisplay(): Status[] {
        return this.cards.slice(this.page * 4, (this.page + 1) * 4)
    },
},
methods: {
    setCards(no: number) {
        this.page = this.page + delta
    },
},

The left and right arrow buttons in the template look like this:

<v-icon v-if="page !==" class="black--text font-weight-bold" 
          @click="setPage(-1)">
          chevron_left</v-icon>

<v-icon
    v-if="columns.length > (page + 1) * 4"
    class="black--text font-weight-bold"
    @click="setPage(1)"
    >chevron_right</v-icon
>

But how can I adjust it to smoothly move to the next card without skipping any? :)

Answer №1

Just follow these steps

computed: {
    carouselItems(): Status[] {
        return [...this.cards, ...this.cards].slice(this.currentIndex, this.currentIndex + 4)
    },
},
methods: {
    previous() {
        this.currentIndex = (this.currentIndex + this.cards.length - 1) % this.cards.length;
    },
    slideRight() {
        this.currentIndex = (this.currentIndex + 1) % this.cards.length;
    },
},

By using [...this.cards, ...this.cards], you can create a cyclic carousel mechanism with minimal code.
Utilizing the remainder operator ensures that your currentIndex always stays within the bounds of the total number of cards. When decrementing, remember to add the length of the array to avoid negative values.

Vue.createApp({
  data: () => ({
    currentIndex: 0,
    cards: new Array(10).fill(null).map((item, index) => ({
      img: "https://picsum.photos/id/" + (index * 10) + "/200",
      text: "Card #" + (index + 1)
    }))
  }),
  computed: {
    carouselItems() {
      return [...this.cards, ...this.cards].slice(this.currentIndex, this.currentIndex + 4)
    },
  },
  methods: {
    previous() {
      this.currentIndex = (this.currentIndex + this.cards.length - 1) % this.cards.length;
    },
    slideRight() {
      this.currentIndex = (this.currentIndex + 1) % this.cards.length;
    },
  },
}).mount("#app")
.carousel-container {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}

.carousel-container > * {
  width: 25%;
}

.carousel-container > * img {
  width: 100%;
}
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
  <button @click="previous">
    &lt;&lt;
  </button>
  <button @click="slideRight">
    &gt;&gt;
  </button>
  <ol class="carousel-container">
    <li v-for="item in carouselItems">
      <img :src="item.img" />
      <p>
        {{ item.text }}
      </p>
    </li>
  </ol>
</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

Leveraging this within the realm of promises utilizing babel

While utilizing Babel, I encountered a problem that I have not yet been able to solve. The issue arises when I use promises within a class method and I require access to the this object of the class inside the promise in order to call class functions. He ...

`Where are functions housed in Vue when dealing with slots?`

When component A acts as the parent to component B, and B has a designated slot for content insertion, the question arises about the placement of a clickHandler. Should it be placed in A or in B? Is it possible to have both options implemented as long as ...

What steps can I take to resolve the "this is undefined" issue in VueJS?

Whenever I include the line this.$store.commit('disconnect');, it throws a "this is undefined" error. Any suggestions on how to resolve this issue? store/index.js : export const state = () => ({ log: false, user: {token: null, id: null, u ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Is there a way to transfer multiple functions using a single context?

Having created individual contexts for my functions, I now seek to optimize them by consolidating all functions into a single context provider. The three functions that handle cart options are: handleAddProduct handleRemoveProduct handleC ...

Unable to fetch data in CakePHP 3.x controller using jQuery AJAX POST

I've been searching everywhere and unfortunately, I can't seem to figure out why the data is not being sent to my controller when posting via ajax. Here's the jQuery code snippet: var newDate = {}; newDate['start' ...

NPM is searching for the package.json file within the user's directory

After completing my test suite, I encountered warnings when adding the test file to the npm scripts in the local package.json. The issue was that the package.json could not be located in the user directory. npm ERR! path C:\Users\chris\pack ...

Obtain the response body in Nest JS middleware

Currently, I am working on developing logging middleware for my project. My main goal is to log the response body specifically in 500 responses. However, I have encountered an issue where the response body is not present in the Response object when using a ...

ReactJS requires HTTP server to transpile babel code before running

I am a beginner when it comes to working with reactjs and I am currently in the process of setting up babel to execute babel code without having to serve HTTP files. Following the instructions on the Package Manager, I have successfully installed it along ...

What steps can be taken to ensure express Node.JS replies to a request efficiently during periods of high workload

I am currently developing a Node.js web processor that takes approximately 1 minute to process. I make a POST request to my server and then retrieve the status using a GET request. Here is a simplified version of my code: // Setting up Express const app = ...

What is the process for retrieving the chosen country code using material-ui-phone-number?

When incorporating user input for phone numbers, I have opted to utilize a package titled material-ui-phone-number. However, the challenge arises when attempting to retrieve the country code to verify if the user has included a 0 after the code. This infor ...

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

Learn the art of generating multiple dynamic functions with return values and executing them concurrently

I am currently working on a project where I need to dynamically create multiple functions and run them in parallel. My starting point is an array that contains several strings, each of which will be used as input for the functions. The number of functions ...

Angular first renders a component before removing another one using ng-If

I have two components that are displayed one at a time using an ngif directive. <app-root> <first-Comp *ngIf="showFirst"></first-Comp> <second-Comp *ngIf="!showFirst"></second-Comp> </app-root> Here are some key ...

Learn how to access the media.navigator.enabled value of Firefox using Javascript

Lately, I've been working on a demo that utilizes getUserMedia() in Javascript to access the webcam of devices and display the video stream on an HTML5 canvas. In cases where browsers do not support getUserMedia(), I have implemented a fallback to a F ...

Determining User Login Status in Laravel using jQuery

While I am familiar with the authentication verification in laravel, I am interested in learning how to verify it using jQuery. Specifically, I want to make changes to my CSS when a user is logged in. By default: body{ background: url('image.jpg ...

retrieve data from an asynchronous request

Utilizing the AWS Service IotData within an AWS Lambda function requires the use of the AWS SDK. When constructing the IotData service, it is necessary to provide an IoT endpoint configuration parameter. To achieve this, another service is utilized to obta ...

How to conceal duplicate items in Angular2

In my Angular 2/4 application, I am fetching data from a web API (JSON) and displaying it in a table. In AngularJS, I use the following code: <tbody ng-repeat="data in ProductData | filter:search | isAreaGroup:selectedArea"> <tr style="backgro ...

Is there a way to display the number of search results in the CodeMirror editor?

After conducting some research on how to integrate the search result count in Codemirror like the provided image, I was unable to find any solutions. I am currently working with Angular and utilizing ngx-codemirror, which led me to realize that editing the ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...