在组件中使用轮播图展示图片信息:
1.下载swiper,5版本为稳定版本
cnpm install swiper@5
2.在组件中引入swiper包和对应样式,若多组件使用swiper,可以把swiper引入到main.js入口文件中:
import 'swiper/css/swiper.css' //引入swiper样式
import Swiper from 'swiper'; //引入swiper
3.在组件中使用:
由于我的组件获取的图片信息由axios请求后端获得,所以要借助属性监听+$nextTick()共同实现轮播图:
<template> <div class="list-container"> <div class="sortList clearfix"> <div class="center"> <!--banner轮播--> <div class="swiper-container" ref="mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide" v-for="carousel in bannerList" :key="carousel.id" > <img :src="carousel.imgUrl" /> </div> </div> <!-- 如果需要分页器 --> <div class="swiper-pagination"></div> <!-- 如果需要导航按钮 --> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> </div> </div> </div> </div> </div> </template> <script> import {mapState} from 'vuex' import Swiper from 'swiper'; export default { name: 'ListContainer', mounted(){ //在vuex仓库中把轮播图和banner图片取出来 this.$store.dispatch('BannerList') }, computed:{ ...mapState({ bannerList:(state)=>state.home.bannerList }) }, watch:{ bannerList:{ handler(newValue,oldValue){ this.$nextTick(()=>{ var mySwiper=new Swiper(this.$refs.mySwiper,{ //配置分页器内容 loop: true, // 循环模式选项 pagination:{ el:".swiper-pagination",//换页器与哪个标签关联 clickable:true//分页器是否可以点击 }, // 如果需要前进后退按钮 navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, //如果需要滚动条 scrollbar: { el: '.swiper-scrollbar', }, }) }) } } } } </script> <style lang="less" scoped> </style>