vue中使用swiper实现图片轮播
1.安装swiper版本5
npm install --save swiper@5
2.引入样式(一般在main.js中引入)
import 'swiper/css/swiper.css'
3.使用的组件中引入并实例化
注:实例化要在dom加载完后,包括v-for等动态数据
import Swiper from 'swiper' const mySwiper = new Swiper('.swiper-container',{ loop: true, pagination :{ el: '.swiper-pagination', clickable :true, }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, })
具体swiper使用见官网 https://www.swiper.com.cn/usage/index.html
4.最佳实例化处理:watch+ $nextTick
watch用来监视数组的变化,$nextTick在下次DOM更新,循环结束之后,执行延迟回调,修改完数据后,立即使用这个方法,获取更新后的dom,确保dom真正的更新完成
computed:{ ...mapState({'pics':state=>state.Home.pic}) }, watch:{ // 监听pics 由[] => [a,b,c,d] // 只能保证数组有数据了,但v-for遍历完不能确定 // 要用到$nextTick:在下次DOM更新,循环结束之后,执行延迟回调,修改完数据后,立即使用这个方法,获取更新后的dom pics:{ handler(newVal,oldVal){ this.$nextTick(function(){ const mySwiper = new Swiper('.swiper-container',{ loop: true, pagination :{ el: '.swiper-pagination', clickable :true, }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }) }) } } },