vue3文字滚动公告组件
时间: 2023-11-08 20:02:12 浏览: 310
您可以使用Vue3开发一个文字滚动公告组件。以下是一个简单的示例代码:
```vue
<template>
<div class="scroll-notice">
<div class="scroll-notice-content" ref="content">
<div v-for="(item, index) in notices" :key="index" class="scroll-notice-item">
{{ item }}
</div>
</div>
</div>
</template>
<script>
import { ref, watch, onMounted, onUnmounted } from 'vue';
export default {
name: 'ScrollNotice',
props: {
notices: {
type: Array,
required: true,
},
interval: {
type: Number,
default: 3000,
},
},
setup(props) {
const contentRef = ref(null);
let scrollTimer = null;
const startScroll = () => {
const content = contentRef.value;
if (content) {
const firstItem = content.children[0];
const itemHeight = firstItem.offsetHeight;
content.appendChild(firstItem.cloneNode(true));
scrollTimer = setInterval(() => {
content.style.transition = 'transform 0.5s';
content.style.transform = `translateY(-${itemHeight}px)`;
setTimeout(() => {
content.style.transition = 'none';
content.style.transform = 'translateY(0)';
content.removeChild(content.children[0]);
content.appendChild(firstItem.cloneNode(true));
}, 500);
}, props.interval);
}
};
onMounted(() => {
startScroll();
});
onUnmounted(() => {
clearInterval(scrollTimer);
});
watch(
() => props.notices,
() => {
clearInterval(scrollTimer);
startScroll();
}
);
return {
contentRef,
};
},
};
</script>
<style scoped>
.scroll-notice {
width: 100%;
height: 100%;
overflow: hidden;
}
.scroll-notice-content {
display: flex;
flex-direction: column;
}
.scroll-notice-item {
margin-bottom: 10px;
}
</style>
```
使用方式:
```vue
<template>
<div>
<ScrollNotice :notices="notices" :interval="3000" />
</div>
</template>
<script>
import ScrollNotice from '@/components/ScrollNotice.vue';
export default {
components: {
ScrollNotice,
},
data() {
return {
notices: ['公告1', '公告2', '公告3'],
};
},
};
</script>
<style>
/* 其他样式 */
</style>
```
阅读全文