Thiết Lập Và Sử Dụng Swiper
Tải xuống và Nhúng CSS và JS
- (1) Cài đặt thư viện Swiper
- (2) Nhập Swiper và các kiểu CSS vào thành phần cần sử dụng carousel
- (3) Tạo các thẻ DOM cần thiết cho Swiper trong thành phần (xem mã HTML mẫu trên trang chủ)
- (4) Khởi tạo đối tượng Swiper
Lưu ý: Khi khởi tạo đối tượng Swiper, cần truyền tham số để lấy phần tử DOM hiển thị carousel. Trang chủ cung cấp cách lấy qua class (class này không được sửa đổi vì nó là của file CSS Swiper). Tuy nhiên, nếu có nhiều carousel trên cùng một trang, điều này có thể gây ra xung đột.
Giải pháp: Thêm thuộc tính ref vào thẻ DOM ngoài cùng của carousel.
<div class="carousel-container" id="myCarousel" ref="currentCarousel">
Sử dụng giá trị ref để lấy DOM:
let myCarousel = new Swiper(this.$refs.currentCarousel, {...});
Khởi Tạo Đối Tượng Swiper Mới
Giải pháp tối ưu: Sử dụng watch + this.$nextTick() Giải thích: Hàm này sẽ trì hoãn việc thực thi callback đến sau lần cập nhật DOM tiếp theo.
Mã hoàn chỉnh như sau:
<template>
<div class="list-container">
<div class="sortList clearfix">
<div class="center">
<!-- Banner Carousel -->
<div class="carousel-container" id="myCarousel">
<div class="carousel-wrapper">
<div class="carousel-slide" v-for="(slide, idx) in slideList" :key="slide.id">
<img :src="slide.imgUrl" />
</div>
</div>
<!-- Phân trang -->
<div class="carousel-pagination"></div>
<!-- Nút điều hướng -->
<div class="carousel-button-prev"></div>
<div class="carousel-button-next"></div>
</div>
</div>
</div>
</div>
</template>
<script>
import Carousel from 'swiper';
import 'swiper/css/swiper.css';
import { mapState } from "vuex";
export default {
name: "index",
mounted() {
this.$store.dispatch("fetchSlideList");
},
computed: {
...mapState({
slideList: state => state.home.slideList
})
},
watch: {
slideList(newVal, oldVal) {
this.$nextTick(() => {
let myCarousel = new Carousel(document.getElementsByClassName("carousel-container"), {
pagination: {
el: '.carousel-pagination',
clickable: true,
},
navigation: {
nextEl: '.carousel-button-next',
prevEl: '.carousel-button-prev',
},
scrollbar: {
el: '.carousel-scrollbar',
},
});
});
}
}
}
</script>
Định Kích Thước Carousel Theo Yêu Cầu
.carousel {
width: 800px;
height: 400px;
}
Cấu Hình Thông Dụng
slidesPerView: 5 - Hiển thị bao nhiêu ảnh mỗi trang
slidesPerGroup: 5 - Số lượng ảnh chuyển khi nhấn nút
const carousel = new Carousel('.carousel', {
loop: true,
slidesPerView: 5,
slidesPerGroup: 5,
navigation: {
nextEl: '.carousel-button-next',
prevEl: '.carousel-button-prev',
},
});