基于vue和swipe开发轮播图组件

网站中,使用轮播图是非常常见的效果的;

项目背景

图片轮播是前端项目必有项,当前有很多效果很酷炫的轮播插件,例如Swiper

  • Swiper常用于移动端网站的内容触摸滑动
  • Swiper是纯javascript打造的滑动特效插件,面向手机、平板电脑等移动终端。
  • Swiper能实现触屏焦点图、触屏Tab切换、触屏多图切换等常用效果。
  • Swiper开源、免费、稳定、使用简单、功能强大,是架构移动终端网站的重要选择!

但是当项目中的图片轮播只需要一个很简单的轮播样式;

我们引用这样一个110k的大插件,就大材小用了。再安利一下,swiper2.x和swiper3.x对移动和PC端支持情况;

这个vue轮播插件只有10k大小,使用十分方便

查看下普通的用法:http://www.swiper.com.cn/usage/index.html

查看Swiper的API文档

先放官网的使用方法。

import Vue from 'vue'
import Swiper from 'vue-swiper'
new Vue({
el: 'body',
components: {Swiper},
methods: {
onSlideChangeStart (currentPage) {
console.log('onSlideChangeStart', currentPage);
},
onSlideChangeEnd (currentPage) {
console.log('onSlideChangeEnd', currentPage);
}
}
});

<swiper v-ref:swiper
        direction="horizontal"
        :mousewheel-control="true"
        :performance-mode="false"
        :pagination-visible="true"
        :pagination-clickable="true"
        :loop=“true”
        @slide-change-start="onSlideChangeStart"
        @slide-change-end="onSlideChangeEnd">
    <div>Page 1</div>
    <div>Page 2</div>
    <div>Page 3</div>
</swiper>

+++看看 API

Properties







Name Type Default Description
direction String "vertical" Could be ‘horizontal’ or ‘vertical’ (for vertical slider).
mousewheel-control Boolean true Set to true to enable navigation through slides using mouse wheel.
pagination-visible Boolean false Toggle (hide/true) pagination container visibility when click on Slider’s container
pagination-clickable Boolean false If true then clicking on pagination button will cause transition to appropriate slide.
performace-mode Boolean false Disable advance effect for better performance.
loop Boolean false Set to true to enable continuous loop mode
==================== ========= ============ ===================

Methods
Name Type Default Description
direction String "vertical" Could be ‘horizontal’ or ‘vertical’ (for vertical slider).
mousewheel-control Boolean true Set to true to enable navigation through slides using mouse wheel.
pagination-visible Boolean false Toggle (hide/true) pagination container visibility when click on Slider’s container
pagination-clickable Boolean false If true then clicking on pagination button will cause transition to appropriate slide.
performace-mode Boolean false Disable advance effect for better performance.
loop Boolean false Set to true to enable continuous loop mode
==================== ========= ============ ===================

Events+++
Name Parameters Description
slide-change-start pageNumber Fire in the beginning of animation to other slide (next or previous).
slide-change-end pageNumber Will be fired after animation to other slide (next or previous).
slide-revert-start pageNumber Fire in the beginning of animation to revert slide (no change).
slide-revert-end pageNumber Will be fired after animation to revert slide (no change).
slider-move offset Callback function, will be executed when user touch and move finger over Swiper and move it. Receives swiper instance and ‘touchmove’ event as an arguments.
================== ================ ============================

而言之,就是当需要一个简单的轮播时,可以选用thebird/Swipe,自己写一个组件。

一般情况,轮播图片因为是要经常换的,故在后台定制,定制内容如下

<div><a href=""><img src=""/></a></div>
<div><a href=""><img src=""/></a></div>
<div><a href=""><img src=""/></a></div>

如果有定制,必须在代码里写的话,也是可以的,造一个data数组swipeInfo

<!--js-->
data:{
    swipeInfo: 
        [
            {href:"http://www.baidu.com", imgSrc:""},
            {href:"http://www.baidu.com", imgSrc:""},
            {href:"http://www.baidu.com", imgSrc:""}
        ]
}, 
components: {
    'swipe-module': require('pagination-swipe')
}

html中绑定该数据

<swipe-module :swipeinfo="swipeInfo"></swipe-module>

Pagination-swipe组件内容

按照swipe构造html框架,添加了pagination块

<!--template.html-->
<div v-el:swipe class='swipe bar-slider'>
    <div class='swipe-wrap'>
        <div v-for="item in swipeinfo"><a :href=item.href><img :src=item.imgSrc /></a></div>
    </div>
    <!-- 分页 -->
    <div class="pagination">
        <span class="swipe-pagination-switch swipe-active-switch" @click="slideToCur(0)"></span>
        <span class="swipe-pagination-switch" @click="slideToCur($index+1)" v-for="item in slideNum"></span>
    </div>
</div>

vue构造组建

//index.js
require('./style.less');
var Swipe = require('swipe');

Vue.component('pagination-swipe',{
    props: ['swipeinfo'],
    template: require('raw!./template.html'),
    data: function() {
        return {
            mySwipe: {},
            slideNum: {},
        };
    },
    ready: function() {
        var self = this;
        //获取子组件中分页小圈圈
        var slides = self.$els.swipe.getElementsByClassName('swipe-pagination-switch');
        self.mySwipe = new Swipe(self.$els.swipe, {
            startSlide: 0,
            continuous: true,
            speed: 1000,
            auto: 4000,
            stopPropagation: false,
            callback: function(index, elem) {
                //渲染分页小圈圈
                for (var i = 0; i < slides.length; i++) {
                    if (i != index) {
                        slides[i].style.opacity = "0.2";
                        slides[i].style.background = "#000";
                    } else {
                        slides[index].style.opacity = "1";
                        slides[index].style.background = "#ee3a4a";
                    }
                }
            },
        });
        self.slideNum = self.mySwipe.getNumSlides() - 1;
    },
    methods: {
        //点击底部小圈圈,跳到其所对应页
        slideToCur: function(index) {
            var self = this;
            self.mySwipe.slide(index, 300);
        },
    }
});

是样式

<!--style.less-->
.swipe {
    overflow: hidden;
    visibility: hidden;
    position: relative;
    height: 200/@rem;
.swipe-wrap {
    position: relative;
    overflow: hidden;
    height: 100%;
div {
    float: left;
    width: 100%;
    position: relative;
    margin: 0;
a {
    width: 100%;
    height: 100%;
    background-position: center 0;
    background-repeat: no-repeat;
    background-color: transparent;
    display: block;
img {
    width: 100%;
    height: 100%;
}
}
}
}
.pagination {
    text-align: center;
    position: relative;
    bottom: 40/@rem;
    cursor: pointer;
}
.swipe-pagination-switch {
    content: "";
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 100%;
    background: #000;
    opacity: 0.2;
    margin: 0 8px;
    z-index: 10;
&:first-child {
     background: #ee3a4a;
 }
}
.swipe-active-switch {
    opacity: 1;
}
}

相关推荐

前基于vue有一个vue-swipe组件,亲测轻量简单易用,基本功能齐全,是做swipe轮播图很好的选择

但是这个有一些问题,

  1. 如果样式放在scoped中,底部小圈圈就不见了~所以,这个的样式使用需要注意样式污染问题.
  2. IE9下没有滑动效果,主要是ie9对css3动画的不兼容

下面是GITHUB上看到的VUE 轮播图的写法(类似Swipe)

<template>
<div class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators" v-show="indicators">
<li v-for="i in indicator" @click="indicatorClick($index)" v-bind:class="{active:$index === index}"><span></span></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<slot></slot>
</div>
<!-- Controls -->
<div v-show="controls" class="carousel-controls hidden-xs">
<a class="left carousel-control" role="button" @click="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
</a>
<a class="right carousel-control" role="button" @click="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
</a>
</div>
</div>
</template>

<script>
import {coerce} from './utils/utils.js'
import $ from './utils/NodeList.js'
export default {
props: {
indicators: {
type: Boolean,
coerce: coerce.boolean,
default: true
},
controls: {
type: Boolean,
coerce: coerce.boolean,
default: true
},
interval: {
type: Number,
coerce: coerce.number,
default: 5000
}
},
data () {
return {
indicator: [],
index: 0,
isAnimating: false
}
},
watch: {
index(newVal, oldVal) {
this.slide(newVal > oldVal ? 'left' : 'right', newVal, oldVal)
}
},
methods: {
indicatorClick(index) {
if (this.isAnimating || this.index === index) return false
this.isAnimating = true
this.index = index
},
slide (direction, next, prev) {
if (!this.$el) { return }
const $slider = $('.item', this.$el)
if (!$slider.length) { return }
const selected = $slider[next] || $slider[0]
$(selected).addClass(direction === 'left' ? 'next' : 'prev')
// request property that requires layout to force a layout
var x = selected.clientHeight
$([$slider[prev], selected]).addClass(direction).on('transitionend', () => {
$slider.off('transitionend').className = 'item'
$(selected).addClass('active')
this.isAnimating = false
})
},
next() {
if (!this.$el || this.isAnimating) { return false }
this.isAnimating = true
this.index + 1 < $('.item', this.$el).length ? this.index += 1 : this.index = 0
},
prev() {
if (!this.$el || this.isAnimating) { return false }
this.isAnimating = true
this.index === 0 ? this.index = $('.item', this.$el).length - 1 : this.index -= 1
},
toggleInterval (val) {
if (val === undefined) { val = this._intervalID }
if(this._intervalID) {
clearInterval(this._intervalID)
delete this._intervalID
}
if(val && this.interval > 0) {
this._intervalID = setInterval(this.next, this.interval)
}
}
},
ready () {
this.toggleInterval(true)
$(this.$el).on('mouseenter', () => this.toggleInterval(false)).on('mouseleave', () => this.toggleInterval(true))
},
beforeDestroy () {
this.toggleInterval(false)
$(this.$el).off('mouseenter mouseleave')
}
}
</script>

<style scoped>
.carousel-control {
cursor: pointer;
}
</style>

~~~~~

未经允许不得转载:WEB前端开发 » 基于vue和swipe开发轮播图组件

赞 (0)