Note: We are using Vue 3 here and I'm new to it myself.
Firstly, we need an array of images, alt texts and optional: a link to click on and text to display alongside the image:
const sliderArray = [ { image: "/images/references/web/besure1.jpg", alt: "Alt text", link: "https://besure.blog", text: "Be Sure Blog Image" }, { image: "/images/references/web/besure2.jpg", alt: "Alt text", link: "https://besure.blog", text: "Be Sure Blog Image" }, { image: "/images/references/web/besure3.jpg", alt: "Alt text", link: "https://besure.blog", text: "Be Sure Blog Image" } ];
Important: The images must exist in the folder "public/images/references/web"!
Next, we will use the ref method, which seems like it was introduced in Vue 3. I had an issue with Vue not re-rendering on state change, and my research led me to this solution (resource link is at the end of the blog post):
import { ref } from 'vue'; const reactiveCount = ref(0);
Then:
export default { data() { return { sliderArray, currentIndex: 0 } }, methods: { next: function() { reactiveCount.value += 1; }, prev: function() { reactiveCount.value -= 1; } }, computed: { currentSlide: function() { return sliderArray[Math.abs(reactiveCount.value) % sliderArray.length]; } } }
Now we have all the <script> functionalities in place and can work on the <template> part:
<div class="image-slider-container"> <div class="left-arrow" @click="prev">❮</div> <div class="right-arrow" @click="next">❯</div> <div class="image-slider"> <transition-group name="fade" tag="div"> <div v-for="i in [currentIndex]" :key="i"> <img :src="currentSlide.image" :alt="currentSlide.alt" /> <a :href="currentSlide.link" target="_blank" rel="noreferrer"> <p>{{ currentSlide.text }}</p> </a> </div> </transition-group> </div> </div>
Finished! Check out the two resources below this post for more information!