Vue 实现类似于 Marquee 组件并添加结束事件
在 Vue 中没有内置的 marquee 组件,但是你可以自己实现一个类似的组件,并且添加结束事件。
下面是一个示例代码,展示了如何实现一个简单的 marquee 组件,并且在结束时触发一个自定义的事件:
<template>
<div class='marquee-container'>
<div class='marquee-content' ref='content' :style="{ transform: `translateX(${offset}px)` }">
{{ text }}
</div>
</div>
</template>
<script>
export default {
props: {
text: {
type: String,
required: true
},
speed: {
type: Number,
default: 2
}
},
data() {
return {
offset: 0,
containerWidth: 0,
contentWidth: 0
};
},
mounted() {
this.containerWidth = this.$el.offsetWidth;
this.contentWidth = this.$refs.content.offsetWidth;
this.startMarquee();
},
methods: {
startMarquee() {
if (this.containerWidth < this.contentWidth) {
this.marqueeInterval = setInterval(() => {
this.offset -= this.speed;
if (this.offset < -this.contentWidth) {
this.offset = this.containerWidth;
clearInterval(this.marqueeInterval);
this.$emit('marquee-end');
}
}, 16);
}
}
}
};
</script>
<style scoped>
.marquee-container {
overflow: hidden;
white-space: nowrap;
}
.marquee-content {
display: inline-block;
transition: transform 0.5s linear;
}
</style>
使用这个 marquee 组件的示例代码:
<template>
<div>
<marquee :text="text" :speed="3" @marquee-end="handleMarqueeEnd" />
</div>
</template>
<script>
import Marquee from './Marquee.vue';
export default {
components: {
Marquee
},
data() {
return {
text: '这是一个 marquee 组件示例'
};
},
methods: {
handleMarqueeEnd() {
console.log('Marquee 结束');
}
}
};
</script>
在这个示例中,Marquee 组件接受两个 props:text 表示要滚动的文本内容,speed 表示滚动速度(默认为 2)。当滚动结束时,组件会触发一个自定义事件 marquee-end,你可以在父组件中监听该事件并执行相应的操作。
注意,这个示例只是一个简单的实现,并不包含所有可能的 marquee 特性,例如暂停、重新开始等。你可以根据自己的需求进行扩展。
原文地址: https://www.cveoy.top/t/topic/qdtN 著作权归作者所有。请勿转载和采集!