[Vuejs]-How to show data according v-for index outside loop

0👍

You can use <template> tag for the v-for loop

  <swiper-slide v-for="(program, index) in programs" :key="index">
    <img :src="program.image"/>
    <div>
      <div class="series-name">
        {{ program.series }}
      </div>

      <div class="song-name">
        {{ program.name }}
      </div>
    </div>
  </swiper-slide>

0👍

Making use of the Swiper events can help:

What is done here?

  • an activeIndex ref is initialized with 0. 0 because the swiper module initializes the swiper with the first activeIndex as 0
  • now we watch every time the slide is changed using the slideChange event
  • every time the slide is changed, the activeIndex ref is updated from the swiper data.
  • now outside the swiper, your extra content is rendered using programs[activeIndex], because now activeIndex gives the position of the program that is currently active in the swiper.
<script lang="ts" setup>
import { ref } from 'vue';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Navigation, Pagination, Scrollbar, A11y } from 'swiper/modules';
import "swiper/css/bundle"

const activeIndex = ref(0);

const onSwiper = (swiper: any) => {
  activeIndex.value = swiper.activeIndex;
};

const onSlideChange = (swiper: any) => {
  activeIndex.value = swiper.activeIndex;
};
const programs = ref([
  {
    image: "https://cdn.pixabay.com/photo/2013/06/30/18/56/butterfly-142506_1280.jpg",
    series: "World Music Series:",
    name: "A Cultural Journey through World Music” Lecture Demonstration",
  },
  {
    image: "https://cdn.pixabay.com/photo/2023/08/08/18/01/butterfly-8177925_1280.jpg",
    series: "Series 2",
    name: "222",
  },
  {
    image: "https://cdn.pixabay.com/photo/2012/03/01/00/55/flowers-19830_1280.jpg",
    series: "Series 3",
    name: "333",
  },
]);
</script>
<template>
  <div class="wrapper">
    <swiper :modules="[Navigation, Pagination, Scrollbar, A11y]" :slides-per-view="1" :space-between="50"
      @swiper="onSwiper" @slideChange="onSlideChange" navigation :pagination="{ clickable: true }">
      <swiper-slide v-for="slide in programs" :key="slide.image">
        <div class="slide-content">
          <img :src="slide.image" alt="slide image" />
        </div>
      </swiper-slide>
    </swiper>
    <div class="extra-content">
      <h2>{{ programs[activeIndex].series }}</h2>
      <h3>{{ programs[activeIndex].name }}</h3>
    </div>
  </div>
</template>

Hope this helps.

Leave a comment