VueJS with bootsrap carousel how to pass images to

2019-07-14 08:01发布

问题:

My requirement is something like this.

  1. I got the list of images from the back-end.
  2. I want to pass those image names to the carousel to display images.

This is my code.

<template>
  <div class="">
    <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">

    <div class="carousel-item active" v-for="banner in banners">
      <img :src="`./assets/${banner}`" alt=""  class="img-fluid"   >

    </div>

  </div>
</div>
  </div>
</template>


<script>

export default {
  name: 'app',
  data () {
    return {
      banners:["logo.png","index.png","Capture.png"]
    }
  },
  methods:{

  }
}
</script>

But this method doesn't work. How do I pass images to my carousel element?

回答1:

The problem is that you're setting all carousel slides to active, so they will all display at once. Use :class to conditionally set the active slide...

<div class="carousel-item" v-for="(banner,idx) in banners" :class="{ active: idx==0 }">
      <img :src="banner" alt="" class="img-fluid">
</div>

Also, make sure the :src="'./assets/${banner}'" reference is actually working to find the images.

Working demo on Codeply

Note: You don't want to use jQuery $('.carousel').carousel(); to load the Carousel since you're already using the data-ride="carousel" attribute. As stated in the Bootstrap 4 docs...

The data-ride="carousel" attribute is used to mark a carousel as animating starting at page load. It cannot be used in combination with (redundant and unnecessary) explicit JavaScript initialization of the same carousel.



回答2:

From https://www.w3schools.com/bootstrap/bootstrap_carousel.asp

The data-ride="carousel" attribute tells Bootstrap to begin animating the carousel immediately when the page loads.

Vue hasn't mounted this component yet on page load. So you gotta initialize the slider only after it has mounted.

So you gotta remove data-ride="carousel", and add $('.carousel').carousel() in the mounted hook (assuming that the jquery $ is available as a global variable). Make sense ?

<template>
  <div class="">
    <div id="carouselExampleSlidesOnly" class="carousel slide">
  <div class="carousel-inner">

    <div class="carousel-item active" v-for="banner in banners">
      <img :src="`./assets/${banner}`" alt=""  class="img-fluid"   >

    </div>

  </div>
</div>
  </div>
</template>


<script>

export default {
  name: 'app',
  data () {
    return {
      banners:["logo.png","index.png","Capture.png"]
    }
  },
  methods:{

  },
  mounted(){
      $('.carousel').carousel();
  }
}
</script>