Nj_96
Nj_96

Reputation: 116

Reload vue-owl-carousel after dynamic data update

Initialized a vue-owl-carousel using dynamic data

<script>

import carousel from 'vue-owl-carousel'

export default {
    components: { carousel },
}
<carousel :items="1">
    <img v-for="(img, index) in images" :src="img" :key="index">
  </carousel>


 data: function() {
    return {
      images: [
        "https://placeimg.com/200/200/any?1",
        "https://placeimg.com/200/200/any?2",
        "https://placeimg.com/200/200/any?3",
        "https://placeimg.com/200/200/any?4"
      ]
    };
  }

Removed one of images from the images array

How to update the owl carousel with new images array?

Upvotes: 0

Views: 1375

Answers (1)

Lucas
Lucas

Reputation: 74

This should work with normal reactivity so im guessing the way how the carousel library is built is just sloppy. My advice is to just build your own carousel. It is really not that and can be a good learning curve.

Nevertheless if you really want to use this library, you could wrap the carousel in a template with a v-if condition. Because when deleting a entry from the images array the carousel needs to be rerendered to show its changes. You can force this by deleting and adding the component to the DOM by toggling the v-if of the template tag. A hacky solution to a problem that shouldnt exist in the first place. But something like this would work:

<template>
  <div id="app">
    <template v-if="toggle">
      <carousel :items="1">
        <template v-for="(img, index) in images">
          <img :src="img" :key="index" />
        </template>
      </carousel>
    </template>

    <button @click="deleteImage">DELETE A IMAGE</button>
  </div>
</template>

<script>
import Carousel from "vue-owl-carousel";
export default {
  name: "App",
  components: { Carousel },
  data() {
    return {
      images: [
        "https://placeimg.com/200/200/any?1",
        "https://placeimg.com/200/200/any?2",
        "https://placeimg.com/200/200/any?3",
        "https://placeimg.com/200/200/any?4",
      ],
      toggle: true,
    };
  },
  methods: {
    deleteImage() {
      this.toggle = false;
      this.images.pop();
      this.$nextTick(() => {
        this.toggle = true;
      });
    },
  },
};
</script>

Ive tested it and it works with the vue-owl-carousel library see sandbox

Upvotes: 2

Related Questions