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

Setting up webpack-hot-middleware in your express application: A step-by-step guide

I am in the process of enabling webpack HMR in my express application. This is not a Single Page Application (SPA). On the view side, I am utilizing EJS and Vue without vue-cli, which means I have to manually set up the vue-loader for the .vue files in web ...

What is the best way to track and display the window.scrollY value in the console using Next.js

Unfortunately, my ScrollToTop component is not functioning correctly within my app. I have exhausted all possible debugging methods but am still unable to determine why the scrollY value is not being logged as expected. Even after moving the snippet to a ...

Leveraging the power of node.js, express, and handlebars to seamlessly render multiple views within a

I'm interested in finding out if there is a way to render multiple views using the res.render() function or another method. In the home.handlebars file, I currently have the following code: <h1>Home</h1> and I would like to display it i ...

Select the hidden HTML option value automatically according to the previous option selected

I am working on a form that includes 2 select tags with the options male and female. The first select, "gender", is visible to the user while the second select, "age", is hidden. <select name="gender"> <option value="1">Male</option> ...

JavaScript - Utilizing appendChild as soon as an element becomes available

I'm encountering an issue with my Chrome Extension where I am unable to detect some of the elements that I need to select within a page. var innerChat = document.querySelector('.chat-list'); My goal is to appendChild to this element, but t ...

Execute the assignment of exports.someFunction from within a callback function

My Express route is set up like this: app.get('/api/:type/:id', api.getItemById); The function api.getItemById resides in the api module within routes. However, inside the api module, I need to execute a function that connects to the database a ...

propagate the previous state using a variable

Currently, I am in the process of refactoring a codebase but have hit a roadblock. My main aim is to update the state when the onChange event of a select box occurs. Specifically, the parameter searchCriteria in my handleFilterChange function is set to in ...

Greetings: Obtaining an array of text within the <td> tags

Here is the HTML Source: <td bgcolor="#ffffbb" colspan=2><font face="Verdana" size=1>2644-3/4<br>QPSK<br><font color="darkgreen">&nbsp;&nbsp;301</font> - 4864</td> I am looking to extract text array wit ...

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...

Exploring JSON data and making precise adjustments in JavaScript

I am attempting to create my own database using JavaScript and JSON, but I have encountered some issues along the way. My main struggle is figuring out how to extract specific content from a JSON file. After doing some research, I came across this code sn ...

Having trouble converting the JQuery result from the REST request into the correct format

Currently, I am working on making a REST request for an array of objects using JQuery. During the execution of the code within the "success" section, everything works perfectly fine - the objects in the array are converted to the correct type. However, I ...

Unable to add ngRoute dependency in Angular

I'm facing an issue while trying to set up a basic Angular route in my current project, encountering the error: Uncaught Error: [$injector:modulerr] I have ensured that I have injected ngRoute as a dependency in my module and included the angular-rou ...

What is the method for setting the content-type in an AJAX request for Android browsers?

I am facing an issue with my ajax call to the Rails server. The response from the server varies between HTML and JSON based on the content type. Surprisingly, this works smoothly on iPhone and desktop browsers like Chrome, but I am encountering a problem o ...

What is the most efficient way to use the $slice operator on a highly nested array in mongoose

I am currently working on slicing a deeply nested array. To illustrate, consider the following structure. I aim to slice this array for pagination purposes. {messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah ...

Inquiry about Date and Time Selection Tool

I am working on a PHP project that includes two textboxes: one for selecting dates and the other for choosing a specific time. What I need assistance with is disabling any times before the selected date in the second timepicker textbox if today's dat ...

AngularJS has encountered an issue with a route resolve promise that has not been completely resolved

I'm currently working on a simple task to manage user roles within routes. The goal is straightforward: Verify the role of the logged-in user on each route (using a resolve function to authenticate the user based on token or login credentials) Direc ...

What is the process to enable a tab in AngularJS using Foundation's tab feature?

Currently, I am utilizing AngularJS in conjunction with Foundations. Visit the official website for more information Within my page, there are two tabs that are functioning correctly as shown below: <tabset> <tab heading="tab1"> </tab ...

Using AngularJS and the ng-show directive, you can set a <div> element to

Objective: My aim is to show the content of a div according to the status of checkboxes, while also ensuring that these divs are visible by default If I have this code snippet: <html> <head> <script src="https://ajax.googleapis.com/ajax/li ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...

Is it possible to run two commands in npm scripts when the first command initiates a server?

When running npm scripts, I encountered an issue where the first command successfully starts a node server but prevents the execution of the second command. How can I ensure that both commands are executed successfully? package.json "scripts": { "dev ...