vue实现无缝轮播(跑马灯效果)

1.首先创建两个vue组件Sweiper.vue和SweiperItem.vue;
2.将两个组件引入页面,Sweiper.vue中用v-model传参(v-model 其实是语法糖,默认属性value和默认事件input);
代码中我是通过v-model的selcted将值传给Sweiper(子组件),自动轮播时子组件再通过触发input事件将即将显示的值传回给父组件
3.核心是要让selected的值传到SweiperItem中,与SweiperItem中的name值相等判该显示哪张图片;


这里的图片没有通过数组用v-for循环,方便大家看其结构形式


Sweiper.vue

<template>
  <div class="Sweiper">
    <slot></slot>
  </div>
</template>
<script>

  export default {
    name: "Sweiper",
    data() {
      return{
        current:''
      }
    },
    props:{
      value:{
        type:String,
        default:""
      },
    },
    mounted(){
      //自动轮播时查找name值用indexOf的方法遍历出当前轮播的下表
      this.names=this.$children.map(child=>{
       return child.name
      });
      this. showImg();
      this. paly()
    },
    methods:{
      showImg(){
        this.current=this.value||this.$children[0].name;
        //当前实例的直接子组件
        this.$children.map(vm=>{
          vm.selected=this.current
        })
      },

      paly(){
        //每次轮播把图片做调整
        this.timer=setInterval(()=>{
          //indexOf返回某个指定字符串首次出现的位置
          const index=this.names.indexOf(this.current);
          let newIndex=index+1;
          //严谨一点
          if (newIndex===this.names.length){
             newIndex=0;
          }
          this.$emit("input",this.names[newIndex])
        },3000)
      }
    },
    watch:{
      //监听value值,发生变化就改变selected
      value(){
        this. showImg()
      }
    },
    beforeDestroy() {
      //实列销毁前
      clearInterval(this.timer)
    }
  };
</script>
<style>
  .Sweiper{
    /*border: 1px solid black;*/
    width: 100%;
    height: 4rem;
    overflow: hidden;
    margin: 0 auto;
    position: relative;
  }
</style>

SweiperItem.vue

<template>
  <transition>
    <div class="Sweiper-item" v-show="isShow">
      <slot></slot>
    </div>
  </transition>
</template>
<script>
  export  default {
    name:"SweiperItem",
    data(){
      return{
        selected:""
      }
    },
    props:{
      name:{
        type:String,
        required:true
      },
    },
    mounted(){

    },
    computed:{
      isShow(){
        return this.selected===this.name;
      }
    }
  };

</script>
<style>
  .v-enter-active,.v-leave-active{
    transition: all 1s linear;
  }
  .v-leave-to{
    transform:translate(-100%);
  }
  .v-enter{
    transform: translate(100%);
  }
  .v-enter-active{
    position: absolute;
    top:0;
    left: 0;
  }
</style>

你可能感兴趣的:(vue实现无缝轮播(跑马灯效果))