第一步: 先下载 npm i swiper -S
第二步:引入
import Swiper from 'swiper' import "swiper/css/swiper.css"
第三步: 引入css的样式
.swiper-container { width: 100%; height: 100%; border: 1px solid gray; } .swiper-slide { width: 120px !important; text-align: center; font-size: 18px; background: #fff; /* Center slide text vertically */ display: -webkit-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; }
第四步: 例子 从本地请求了一个json数据。使用swiper
export default class All extends Component { state = { list: [] } componentDidMount() { Axios.get('/data.json').then(res => { this.setState(() => { return { list: res.data.data.goodsList } }) }) new Swiper('.swiper-container', { slidesPerView: 3, spaceBetween: 30, slidesPerGroup: 3, loop: true, // 循环模式选项 loopFillGroupWithBlank: true, pagination: { // 如果需要分页器 el: '.swiper-pagination', clickable: true, }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }) } render() { const { list } = this.state console.log(list) return ( <div className='page-all'> <div className="swiper-container"> <div className="swiper-wrapper"> { list.map(item => { return ( <div className="swiper-slide" key={item.id}> <p><img src={item.imgurl} /></p> </div> ) }) } </div> {/* 如果需要分页器 */} <div className="swiper-pagination"></div> {/* 如果需要导航按钮 */} <div className="swiper-button-next"></div> <div className="swiper-button-prev"></div> </div> </div> ) } }
效果图: