子组件的封装
<template>
<div class="line-scroll-animation">
<div
class="animation-list-container"
@mouseenter="stopScroll()"
@mouseleave="startScroll()"
:class="{animation: active}"
:style="{transform: `translateY(${scrolling * - stepHeight}px)`}">
<slot v-for="(item, index) in listData" :data="item" :index="index"></slot>
</div>
</div>
</template>
<script>
export default {
name: 'LineScrollAnimation',
props: {
// 传过来的列表数据
list: {
type: Array,
default: () => [],
},
min: {
type: Number,
default: 0,
},
// 每次滚动的距离
stepHeight: {
type: Number,
default: 0,
},
},
data() {
return {
timeout: null,
scrolling: 0,
// 控制动画
active: true
};
},
watch: {
// 列表数据变动 重新加载滚动
list: {
handler(){
this.resetScroll()
},
immediate: true
},
},
computed: {
listData() {
if(!this.list) return []
// 传过来的数据 大于 最小数
if (this.list.length > this.min) {
// 以最小数截取列表数据
let repeat = this.list.slice(0, this.min)
return [...this.list, ...repeat];
} else {
return this.list || [];
}
},
scrollMax(){
return this.list.length
}
},
methods: {
startScroll() {
if(!this.list || this.list.length <= this.min) return
this.active = true
if (this.timeout) {
clearTimeout(this.timeout);
}
if(this.scrolling < this.scrollMax){
this.scrolling++
} else {
this.active = false
this.scrolling = 0
}
this.$nextTick(() => {
this.timeout = setTimeout(() => {
this.startScroll()
}, 3000);
})
},
stopScroll(){
clearTimeout(this.timeout)
},
resetScroll(){
clearTimeout(this.timeout)
this.active = false
this.scrolling = 0
this.$nextTick(() => {
this.startScroll()
})
}
},
beforeDestroy() {
clearTimeout(this.timeout);
},
};
</script>
<style scoped>
.line-scroll-animation {
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
.line-scroll-animation .animation-list-container {
width: 100%;
position: absolute;
}
.line-scroll-animation .animation-list-container.animation{
transition: transform .33s linear
}
</style>
父组件使用
1.引入 import LineScrollAnimation from “…/components/base/LineScrollAnimation”;
2.使用
<LineScrollAnimation
:min="3"
:stepHeight="30"
:list="rankingList"
>
<template slot-scope="{ data, index }">
<div class="ranking-list-item" :key="index">
<div class="ranking-list-trademark">{{ index + 1 }}</div>
<div class="ranking-list-place">{{ data.place }}</div>
<div class="ranking-list-text">{{ data.text }}</div>
<div class="ranking-list-num">{{ data.num }}</div>
</div>
</template>
</LineScrollAnimation>
<script>
// 列表数据
data(){
return{
rankingList: [
{
place: "1",
text: "列表1",
num: 111,
},
{
place: "2",
text: "列表2",
num: 222,
},]
}
</script>