The first item in Swiper is incorrectly displayed after the initial cycle, even though the data is accurate

Currently, I am incorporating the slider functionality in Vue using the Swiper framework. Although everything seems to be functioning properly, there is a minor issue that arises when filtering the data and completing the first cycle after scrolling. The filter correctly returns the desired items, but the initial rendered item is incorrect.

An interesting observation I made was that this discrepancy only occurs when sliding "down", while it works perfectly fine when sliding "up".

Upon further analysis, I suspect that the root of the problem lies in the updating process. Ideally, I would like to update the information before returning the filtered data in the getter function; however, I am unsure how to reference my swiper instance. It's essential to note that Vuex should not have explicit knowledge about frontend operations.

The following is my Vuex getter responsible for filtering the data (which consistently produces accurate results):

  filterByCategory(state, getters, rootState) {
      if (rootState.shared.selectedCategory !== 'All') {
        return state.items.filter(
          item => crypto.decrypt(item.category) === rootState.shared.selectedCategory,
        );
      }
      return state.items.filter(item => item.title.toLowerCase().indexOf(getters.filters.searchString.toLowerCase()) >= 0);
    },

To access my computed data using mapGetter, I employ the following syntax:

...mapGetters('data', ['filterByCategory']),

Below is the component responsible for rendering the slides (notably, the first product-slide appears incorrectly):

  <swiper
    ref="productSlider"
    :options="swiperOptions"
    class="product-slider"
    @slideChange="onSlideChange"
  >
    <product-slide
      v-for="item in items"
      :key="item.id"
      :item="item"
    /> 
    <div
      slot="pagination"
      class="product-slider__pagination"
    />
  </swiper>

Additionally, here are the functions within the data() and methods used to update the swiper:

props: {
    items: {
      type: Array,
      default: () => [],
      required: true,
    },
  },
  data() {
    const self = this;
    return {
      swiperOptions: {
        direction: 'vertical',
        loopedSlides: 1,
        spaceBetween: 30,
        slidesPerView: 1,
        effect: 'fade',
        loop: true,
        mousewheel: {
          invert: false,
        },
        pagination: {
          el: '.product-slider__pagination',
          clickable: true,
          dynamicBullets: true,
          dynamicMainBullets: 1,
        },
      },
    };
  },
  computed: {
    swiper() {
      return this.$refs.productSlider.swiper;
    },
  },
  updated() {
    if(this.swiper) {
      this.swiper.update();
      console.log('swiper-updated');
    }
  },
  beforeDestroy() {
    if(this.swiper) {
      console.log('swiper-before-destroy');
      this.swiper.destroy();
    }
  },
  watch: {
    items(newValue, oldValue) {
      if (this.swiper) {
        console.log(this.items);
        this.$nextTick(() => {
          this.swiper.update();
        });
      }
    },
  },
  methods: {
    onSlideChange() {
      console.log('Slide did change');
    },
  }

I've exhausted all possible solutions but seem unable to pinpoint where the issue lies. Even enabling observer: true has not resolved the matter. At this point, I'm uncertain whether the fault is mine or an inherent flaw within the framework. Any assistance would be greatly appreciated.

You can view a simple exemplar on CodePen.

Answer №1

After much searching, I stumbled upon the solution to my problem in this Github discussion!

To resolve the issue, here's what I did:

I initialized a variable called show within the data() function, and created a method named reRender() with the following content:

  reRender(){
      this.show = false
      this.$nextTick(() => {
        //re-render start
        this.show = true
        this.swiper.destroy();
        this.$nextTick(() => {
            //re-render end
            this.swiper.update();
        })
      })
    }

Then, I included the attribute :v-if="show" in the <swiper></swiper> component.

In my watcher, I invoked the reRender() function.

Though I am uncertain of its accuracy, it seems to be functioning correctly at present.

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

Guide to animating the height of a div using jQuery:

I'm hoping to create a cool animation effect where a certain part of a div expands to 100% width when clicked, and then reverts back to its original height on a second click. I've tried writing some code for this, but it's not working as exp ...

Attempting to utilize JavaScript in order to reset a text input field

I'm having trouble clearing a text field using this function. The alert is working but the field remains unchanged. What could be the issue? This function is designed to work on any text field. <!DOCTYPE html> <html> <head> ...

Q.all failing to execute promises within array

Hey all, I'm currently facing an issue while attempting to migrate users - the promises are not being called. User = mongoose.model 'User' User.find({"hisId" : {$exists : true}}).exec (err, doc)-> if err console.error err ...

Stopping setTimeout when leaving the current page: Is it possible?

Good evening, I am looking for advice on how to cancel a setTimeout function when a user navigates to other pages (for example, by clicking other links or pressing the back button in the browser, but not by changing tabs). I have attempted to use the windo ...

Utilize ngx-filter-pipe to Streamline Filtering of Multiple Values

Need assistance with filtering an array using ngx-filter-pipe. I have managed to filter based on a single value condition, but I am unsure how to filter based on multiple values in an array. Any guidance would be appreciated. Angular <input type="text ...

Creating personalized nuxt-links/routes for each article: A comprehensive guide to Nuxt.js

I'm struggling to implement dynamic routing with nuxt-link. On the main page (localhost:3030/), I have articles fetched from a backend server using axios. Each article needs to link to the route localhost:3030/articles/:postid. The value for :posti ...

Use the asset module instead of the file-loader when adding additional loaders in the chain

My webpack configuration includes the following module for processing SCSS files: { test: /atffonts\.scss$/, use: [ { loader: 'file-loader', options: { name: 'style/[name].css', ...

Unable to access a nested JSON object that has a repeated name

I'm relatively new to working with JSON, so the issue I'm facing may be simple, but I haven't been able to find a similar problem on stackoverflow. Here's my question: My goal is to access a nested JSON object like: pizza.topping.ratin ...

To enable the radio button upon clicking the list item in JavaScript, simply check the radio button

I am working with radio buttons Here is the HTML code: <input type="radio" class="first" name="bright" checked> <input type="radio" class="second" name="bright" > <input type=" ...

End the child process.execution after a specific amount of time

I have been searching for information on child process waiting time or response waiting time, but I haven't found anything useful. I'm in need of something like that, so I hope someone can assist me. When I look at the code below, I am printing ...

Deliver real-time notifications to linked users by leveraging socket.io and node.js

Is there a solution for sending real-time updates to connected clients every second without using the setInterval() function in nodejs and socket.io? Please provide an alternative method that fits my specific scenario. ...

Invoke a parent method from a nested child component in Vue

After setting up a project with vue-cli using the webpack template, I decided to incorporate a reusable bootstrap modal dialog in the App component. To achieve this, I created a method called showMessage in the App component that handles displaying the mod ...

Angular tutorial: Organizing data by date only

This is my first time building an Angular app. I am fetching JSON data from an API using a factory service to get football match fixtures. My goal is to group these fixtures by date while disregarding the time component. The date string in the JSON is fo ...

How can I eliminate the scrollbar from appearing on all browsers when visiting my website?

I've encountered an issue while building my portfolio with React.js. I'm having trouble removing the scrollbar. I've attempted using overflow: hidden for the parent element and overflow: scroll for the child div, but it's not producing ...

Enter the variable into the parameter

I'm working with some Javascript code: document.getElementById("Grid").style.gridTemplateRows = "repeat(3, 2fr)"; I'm trying to insert a variable as an argument to modify my CSS style. When I attempt the following: "repe ...

Managing Express Sessions: Best Practices

I am currently working on handling authentication sessions in a Node.js, Express, Passport app. Despite using express-session and registering new users, the authentication still doesn't work. Below is the code snippet for the local strategy: // Loca ...

Convert the data received from jQuery $.parseJSON into HTML code

I am using $.parseJSON to retrieve data from a specific URL. The link I receive contains {"status":"ok", "message":'<form><input type="text" name="" value=""> </form>'} Now, I want to add the "message" part to my content. $. ...

top technique for chaining promises in a sequence

At the moment, I have several functions that return promises like the example below: function action_one(){ return new Promise((resolve, reject)->{ ... }); } I am looking for a way to wait for one promise to finish before moving on to t ...

IBM Watson Conversation and Angular Integration

After recently diving into Angular, I am eager to incorporate a Watson conversation bot into my angular module. Unfortunately, I'm facing an issue with including a library in Angular. To retrieve the Watson answer, I am utilizing botkit-middleware-wat ...

Is it possible for my code in ReactJS to utilize refs due to the presence of backing instances?

When working with ReactJS components, I often piece together JSX elements to create my code. For example, take a look at the snippet below. I recently came across this page https://facebook.github.io/react/docs/more-about-refs.html which mentions that "Re ...