【在VUE中使用swiper轮播组件】
1.安装
npm install swiper vue-awesome-swiper --save
注意:该安装方法安装的最新版的vue-awesome-swiper(@4),对应的是swiper6,
然而,swiper6仅仅与vue3兼容,swiper6的文档也是英文,问题可能不易解决
所以,我们这里安装vue-awesome-swiper(@3),npm install vue-awesome-swiper --save-dev
2.引入
按照百度说法,
在mian.js中引入
import VueAwesomeSwiper from 'vue-awesome-swiper'
Vue.use(VueAwesomeSwiper)
轮播可以全局引入或者局部引入
在组件中引入
1 <script> 2 import { swiper, swiperSlide } from "vue-awesome-swiper"; 3 import "swiper/dist/css/swiper.css"; 4 export default { 5 name: 'HelloWorld', 6 components: { 7 swiper, 8 swiperSlide 9 }, 10 data () {34 },40 } 41 </script>
发现VUE保持找不到swiper.css,此刻需要安装swiper、
npm install swiper --save,但是没有带版本,默认安装的时swiper6,依旧有问题
所以
3. 正确安装(重点):
npm install vue-awesome-swiper@3 --save-dev
4.完整代码:
<template> <div class="recommendPage"> <swiper :options="swiperOption" ref="mySwiper"> <swiper-slide v-for="(item, idx) in bannerList" :key="idx"> <img :src="item.url" alt=""> </swiper-slide> <div class="swiper-pagination" slot="pagination"></div> <div class="swiper-button-prev" slot="button-prev"></div> <div class="swiper-button-next" slot="button-next"></div> </swiper> </div> </template> <script> import { swiper, swiperSlide } from "vue-awesome-swiper"; import "swiper/dist/css/swiper.css"; export default { name: 'HelloWorld', components: { swiper, swiperSlide }, data () { return { bannerList: [ { url: require("../../assets/img/banner1.png") }, { url: require("../../assets/img/banner2.png") }, { url: require("../../assets/img/banner3.png") }, ], swiperOption: { // slidesPerView: 1, loop: true, // 循环模式 autoplay: { delay: 3000, stopOnLastSlide: false, disableOnInteraction: false }, speed: 2000, // effect: 'fade', // 显示分页 pagination: { el: ".swiper-pagination", clickable: true //允许分页点击跳转 }, // 设置点击箭头 navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev" } } } }, computed: { swiper() { return this.$refs.mySwiper.swiper; } }, mounted() { // current swiper instance // 然后你就可以使用当前上下文内的swiper对象去做你想做的事了 console.log("this is current swiper instance object", this.swiper); // this.swiper.slideTo(3, 1000, false); }, created() { const vm = this; }, methods: { } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style lang="less" scoped> @import "index"; .recommendPage { width: 100%; height: 100%; } </style>