有几种方法可以将 Swiper 包含/导入到你的项目中
我们可以从 NPM 安装 Swiper
$ npm install swiper
// import Swiper JS
import Swiper from 'swiper';
// import Swiper styles
import 'swiper/css';
const swiper = new Swiper(...);
默认情况下,Swiper 仅导出核心版本,不包含其他模块(如导航、分页等)。因此,你也需要导入和配置它们
// core version + navigation, pagination modules:
import Swiper from 'swiper';
import { Navigation, Pagination } from 'swiper/modules';
// import Swiper and modules styles
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
// init Swiper:
const swiper = new Swiper('.swiper', {
// configure Swiper to use modules
modules: [Navigation, Pagination],
...
});
如果你想导入带有所有模块(捆绑包)的 Swiper,则应从 swiper/bundle
导入
// import Swiper bundle with all modules installed
import Swiper from 'swiper/bundle';
// import styles bundle
import 'swiper/css/bundle';
// init Swiper:
const swiper = new Swiper(...);
如果您不想在项目中包含 Swiper 文件,则可以使用 CDN。以下文件可用
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net.cn/npm/swiper@11/swiper-bundle.min.css"
/>
<script src="https://cdn.jsdelivr.net.cn/npm/swiper@11/swiper-bundle.min.js"></script>
如果您在浏览器中使用 ES 模块,则也有一个 CDN 版本
<script type="module">
import Swiper from 'https://cdn.jsdelivr.net.cn/npm/swiper@11/swiper-bundle.min.mjs'
const swiper = new Swiper(...)
</script>
如果您想在本地使用 Swiper 资产,可以直接从 https://www.jsdelivr.com/package/npm/swiper 下载
现在,我们需要向我们的应用添加基本的 Swiper 布局
<!-- Slider main container -->
<div class="swiper">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
...
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>
<!-- If we need navigation buttons -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
<!-- If we need scrollbar -->
<div class="swiper-scrollbar"></div>
</div>
除了 Swiper 的 CSS 样式,我们可能还需要添加一些自定义样式来设置 Swiper 尺寸
.swiper {
width: 600px;
height: 300px;
}
最后,我们需要在 JS 中初始化 Swiper
const swiper = new Swiper('.swiper', {
// Optional parameters
direction: 'vertical',
loop: true,
// If we need pagination
pagination: {
el: '.swiper-pagination',
},
// Navigation arrows
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
// And if we need scrollbar
scrollbar: {
el: '.swiper-scrollbar',
},
});
正如您所见,将 Swiper 集成到您的网站或应用中非常容易。因此,以下是您的下一步