Vue-powered carousel having trouble rotating properly

I recently came across a carousel created using vanilla javascript and html. I attempted to convert it to Vue, but encountered some challenges. The carousel is supposed to dynamically pull images from a SharePoint list. However, in my version, the images are stacked vertically instead of rotating as intended. Below is the code snippet with an array of objects simulating a SharePoint list:

new Vue({
  el: '#carouselApp',
  data: function() {
    return {
      images: [{
          src: 'https://images.unsplash.com/photo-1533048324814-79b0a31982f1?ixlib=rb-1.2.1&dpr=1&auto=format&fit=crop&w=416&h=312&q=60',
          text: 'Tech trends',
          num: 0
        },
        {
          src: 'https://thumbs.dreamstime.com/b/rainbow-butterfly-colorful-wings-colored-all-colors-vibgyor-very-attractive-placed-black-white-30774133.jpg',
          text: 'Tech Spot',
          num: 1
        },
        {
          src: 'https://image.shutterstock.com/image-photo/color-butterfly-isolated-on-white-260nw-570560110.jpg',
          text: 'Tech Idea',
          num: 2

        },
        {
          src: 'http://static.nautil.us/16630_c2e2a6521fbf5aab3693d9dd7ca9cb1e.jpg',
          text: 'Yellowy Orange',
          num: 3

        },
        {
          src: 'https://static.independent.co.uk/s3fs-public/thumbnails/image/2020/01/07/13/monarch-butterfly.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70',
          text: 'Tech chip',
          num: 4
        }
      ]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<!DOCTYPE html>
<html lang="en" xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="/SiteAssets/_script/vue.js"></script>
  <style>
    .glyphicon {
      color: #ffffff
    }
  </style>

</head>

<body>
  <!-- https://www.w3schools.com/bootstrap/bootstrap_carousel.asp -->
  <div id="carouselApp" class="container">
    <div class="row">
      <div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="width:501px;margin-top:5px">
        <!-- Indicators -->
        <ol class="carousel-indicators" v-for="(img, index) in images.length">
          <li data-target="#carousel-example-generic" :data-slide-to="index" class="active"></li>
        </ol>

        <!-- Wrapper for slides -->
        <div class="carousel-inner" role="listbox" v-for="(item, index) in images">
          <div class="item active">
            <a href="/News/Pages/Default.aspx"><img v-bind:src="item.src" alt="..." style=" width:100%;height:303px"></a>
            <div class="carousel-caption">
              {{item.text}}
            </div>
          </div>
        </div>

        <!-- Controls -->
        <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
          <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>
        </a>
        <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
          <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
          <span class="sr-only">Next</span>
        </a>
      </div>
    </div>

  </div>

</body>

</html>

Answer №1

When comparing Vue and jQuery, the approach to handling tasks differs significantly.

In Vue, the approach is more declarative, while in jQuery it tends to be more imperative. A Vue mentality would involve breaking a carousel into components, such as a CarouselContainer for specifying dimensions and a CarouselSlide for displaying images. It might look like this:

// Carousel.vue
...
<CarouselContainer /* props, etc.. */>
  <CarouselSlide /* ... */>
    <!-- maybe some children -->
  </CarouselSlide>
</CarouselContainer>
...

An article provides insights on structuring carousels in Vue, with a relevant repository link.

To illustrate, you can simplify code in Vue for creating a basic carousel functionality: View CodePen example here

/*Modified carousel from: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_autohttps://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto*/
/*Plan to introduce image list later*/
new Vue({
  el: '#carouselApp',
  methods: {
    browse(direction) {
      if (direction === 'forward') {
        if (this.currentIndex + 1 === this.images.length) {
          this.currentIndex = 0;
        } else {
          this.currentIndex++;
        }
      }
      if (direction === 'backward') {
        if (this.currentIndex === 0) {
          this.currentIndex = this.images.length - 1;
        } else {
          this.currentIndex--;
        }
      }
    }
  },
  data: function() {
    return {
      currentIndex: 0,
      images: [{
          src: 'https://images.unsplash.com/photo-1533048324814-79b0a31982f1?ixlib=rb-1.2.1&dpr=1&auto=format&fit=crop&w=416&h=312&q=60',
          text: 'Tech trends',
          num: 0
        },
        {
          src: 'https://thumbs.dreamstime.com/b/rainbow-butterfly-colorful-wings-colored-all-colors-vibgyor-very-attractive-placed-black-white-30774133.jpg',
          text: 'Tech Spot',
          num: 1
        },
        {
          src: 'https://image.shutterstock.com/image-photo/color-butterfly-isolated-on-white-260nw-570560110.jpg',
          text: 'Tech Idea',
          num: 2

        },
        {
          src: 'http://static.nautil.us/16630_c2e2a6521fbf5aab3693d9dd7ca9cb1e.jpg',
          text: 'Yellowy Orange',
          num: 3

        },
        {
          src: 'https://static.independent.co.uk/s3fs-public/thumbnails/image/2020/01/07/13/monarch-butterfly.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70',
          text: 'Tech chip',
          num: 4
        }
      ]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<!DOCTYPE html>
<html lang="en" xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="/SiteAssets/_script/vue.js"></script>
  <style>
    .glyphicon {
      color: #ffffff
    }
  </style>

</head>

<body>
  <!-- https://www.w3schools.com/bootstrap/bootstrap_carousel.asp -->
  <div id="carouselApp" class="container">
    <div class="row">
      <div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="width:501px;margin-top:5px">
        <!-- Indicators -->
        <ol class="carousel-indicators" v-for="(img, index) in images.length">
          <li data-target="#carousel-example-generic" :data-slide-to="index" class="active"></li>
        </ol>

        <!-- Wrapper for slides -->
        <div class="carousel-inner" role="listbox" v-for="(item, index) in images">
          <div v-if="currentIndex === index" class="item active">
            <a href="/News/Pages/Default.aspx"><img v-bind:src="item.src" alt="..." style=" width:100%;height:303px"></a>
            <div class="carousel-caption">
              {{item.text}}<br/>
              {{currentIndex + 1}} / {{images.length}}
            </div>
          </div>
        </div>

        <!-- Controls -->
        <a @click="browse('backward')" class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
          <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>
        </a>
        <a @click="browse('forward')" class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
          <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
          <span class="sr-only">Next</span>
        </a>
      </div>
    </div>

  </div>

</body>

</html>

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

What is the best way to use setInterval with an Express application?

I've been searching online for a while, experimenting with different methods and coming up with unconventional solutions to my issue without making any progress. My main query is, how can I set an interval in my express.js application to run every 30 ...

The ajax request functions smoothly on the OS X Paw app and cURL, but does not work properly when coded in Javascript / jQuery

Currently delving into the world of ajax requests, I've been utilizing the Paw app to troubleshoot one. Surprisingly, the request functions flawlessly within Paw itself and even the cURL code generated by Paw works like a charm. However, the JavaScrip ...

Retrieve the value of a JSON array containing only a single object using jQuery

In my project, I have a jQuery file and a PHP file. If the PHP file successfully completes the process, it returns the value 2 using `echo json_encode(2)`. I am able to catch this value in the jQuery file and display a string on an HTML div without any iss ...

Every time I click, the click event is getting attached repeatedly through the on method

Here is the HTML code that I am working with: <div class="connect"> <ul> <li><a href="#">Assign a Task</a></li> <li><a attr="viewCard" href="#">View Ca ...

Having trouble with Javascript Array Push and Splice not functioning properly?

My goal is to replace the value "3" with "4" in the array. After this operation, only "1":"2" will remain in the array. const array = []; array.push({ "1": "2" }) array.push({ "3": "4" }) const index = array.indexOf(3); if (index > -1) { array.sp ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

Adding and Removing Attributes from Elements in AngularJS: A Step-by-Step Guide

<input name="name" type="text" ng-model="numbers" mandatory> Is there a way to dynamically remove and add the "mandatory" class in Angular JS? Please note that "mandatory" is a custom class that I have implemented. Thank you. ...

I would appreciate it if someone could clarify how the rendering process occurs in React in this specific scenario

let visitor = 0; function Mug({name}) { visitor = visitor + 1; console.log(name, visitor); return <h2>Coffee mug for visitor #{visitor}</h2>; } return ( <> <Mug name={"A"}/> <Mug name={"B&qu ...

Is pl/pgsql block code supported by postgres-nodejs?

I am attempting to define a custom UUID variable that can be utilized across multiple queries within a transaction. Initially, I attempted using a JavaScript variable which ultimately defeated the purpose of declaring the variable on the server side. The ...

"Looking to access your Express app in a VM from the internet? Here's how

I have an express app running on a Node.js server hosted on Azure Linux VM, and I am looking to access this website from my personal computer. const express = require('express'); const app = express(); app.listen(3000, () => { console.lo ...

Issue encountered during compilation of JavaScript in Vue framework with Rollup

Struggling to compile my Vue scripts with rollup. The error I'm facing is [!] Error: 'openBlock' is not exported by node_modules/vue/dist/vue.runtime.esm.js, imported by src/js/components/TestButton.vue?vue&type=template&id=543aba3 ...

The file could not be located on the server during the project build and upload process

Presently, I'm engrossed in a project involving Angular 9 and ASP Core 3. You can find the website at: Nevertheless, encountering an error when trying to access this URL: http://mag-testcpl.astromap.ir/assets/vendors/global/toastr.css The culprit ...

Is there a chance of a race condition occurring during file uploads when processed individually through AJAX with PHP?

I have created a form for uploading multiple files. <form id="myuploadform" enctype="multipart/form-data"> <input id="uploadedFiles" name="uploadedFiles" type="file" class="form-control&qu ...

Transforming background color upon click using Vue

I'm trying to change the background color from blue to a different color when a button is clicked. However, the code I've written so far doesn't seem to be working. HTML <script src="https://cdn.jsdelivr.net/npm/vue"></script> ...

Launching a modal by passing data in an MVC environment

I am struggling with a task where I have a list of objects, and upon clicking on any of them, I want a modal to open displaying the data of the clicked object. Despite thinking it would be simple, I just can't seem to get it to work. My goal is to pas ...

Connecting users from a mobile website to a particular item within the Amazon application

Recently, I've been working on linking from my mobile site to a particular item within the Amazon app. My JavaScript code includes a try/catch block that redirects users to the webpage if they don't have the app installed. However, I've foun ...

Tips on organizing a JSON object for a JavaScript project

For my project, I am designing a data structure that utilizes JSON. My goal is to create an efficient method for searching and editing the JSON object. Which structure would be considered standard in this scenario? Is there a preferred way to implement eit ...

Effortlessly transforming a massive JSON into an Array using ReactJS

I have a large JSON dataset containing information on over 2000 cities. I want to use this data in my React app, but first I need to convert it into an array. A similar question has been asked before, but I couldn't find any answers that fit my specif ...

Utilize Object literal manipulation to include properties in a specific sequence

Working on a tool to generate Nassi-Shneiderman diagrams online, where each diagram is represented as an object literal with unlimited possible children. As I aim to add a sequence into the while loop following the first sequence, I encounter the challeng ...