webpack项目中通过npm安装和使用Swiper

Swiper的npm安装

  1. npm安装
npm install swiper --save-dev
  1. 添加HTML元素
<div class="swiper-container">
    <div class="swiper-wrapper">
        <div class="swiper-slide">Slide 1</div>
        <div class="swiper-slide">Slide 2</div>
        <div class="swiper-slide">Slide 3</div>
    </div>
    <div class="swiper-pagination"></div>
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
</div>
  1. 在入口文件中引入CSS样式和Swiper
  • 我这里是src/js/index.js文件中:
// import Swiper JS
import Swiper from 'swiper';
// import Swiper styles
import 'swiper/swiper-bundle.css';
  1. 如果需要使用分页器等功能,需要修改导入Swiper的代码
import Swiper from 'swiper' (修改为)=>  import Swiper, { Navigation, Pagination } from 'swiper'
  1. 初始化Swiper
Swiper.use([Navigation, Pagination]); // 使用需要的功能
const mySwiper = new Swiper('.swiper-container', {
  loop: true,
  pagination: {
    el: '.swiper-pagination', // 分页器
  },
  navigation: {
    nextEl: '.swiper-button-next', //切换箭头
    prevEl: '.swiper-button-prev',
  },
})
posted @ 2020-10-28 23:37  必慎  阅读(4559)  评论(1编辑  收藏  举报