R
R
Renhor2019-04-23 12:40:06
Vue.js
Renhor, 2019-04-23 12:40:06

Asynchronous loading of slides does not work in my slider. How to fix?

Good day!
I have a slider with a template

<slider>
      <slide>1</slide>
      <slide>2</slide>
      <slide>3</slide>
</slider>

In this form, everything works fine :) But I need to adapt it to load slides from the server. Now in the Slider component, I initialize the slides through slots:
initSlides() {
  this.slides = this.$slots.default.filter((item) => item.componentOptions);

  this.slides.forEach((item, index) => {
    item.componentOptions.propsData.index = index;
  });
}

This method is called in the created hook. Further, the structure of the template, when loading slides from the store (and from there, respectively, from the database):
<slider :itemsToShow="4" :controls="true" :pagination="true" :autoPlay="false">
  
  <slide v-for="(screen, i) in screenshots" :key="'screen' + i">
    <img :src="screen" alt="">
  </slide>

</slider>

Screenshots is just an array that is loaded from the database using axios.
Returning to JS, I understand that at the time of the created hook, the slides (or rather $slots.default) have not yet been loaded and mounted, so the console swears that it cannot filter them and bugs start from here.
It turns out that I need to change this piece of code somehow, but I still don’t understand how, please help!
methods: {
  initSlides() {
    this.slides = this.$slots.default.filter((item) => item.componentOptions);

    this.slides.forEach((item, index) => {
      item.componentOptions.propsData.index = index;
    });
  }
},
created() {
  this.initSlides();
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2019-04-23
@Renhor

Just give the slider the v-if="slides" attribute

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question