vue实现公告
Vue 实现公告功能的方法
公告功能通常需要实现滚动展示、自动切换或固定显示的效果。以下是几种常见的实现方式:
使用 marquee 标签实现滚动公告
<template>
<marquee behavior="scroll" direction="left">
{{ announcement }}
</marquee>
</template>
<script>
export default {
data() {
return {
announcement: '这是一条重要公告内容...'
}
}
}
</script>
使用 CSS 动画实现平滑滚动
<template>
<div class="announcement-container">
<div class="announcement-content">
{{ announcement }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
announcement: '系统将于今晚23:00进行维护升级,请提前保存工作...'
}
}
}
</script>
<style>
.announcement-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.announcement-content {
display: inline-block;
animation: scroll 15s linear infinite;
}
@keyframes scroll {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
实现多条公告轮播
<template>
<div class="announcement-box">
<transition name="fade" mode="out-in">
<div :key="currentIndex" class="announcement-item">
{{ announcements[currentIndex] }}
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
announcements: [
'公告1:系统升级通知',
'公告2:新功能上线',
'公告3:维护时间调整'
],
currentIndex: 0,
interval: null
}
},
mounted() {
this.startRotation()
},
beforeDestroy() {
clearInterval(this.interval)
},
methods: {
startRotation() {
this.interval = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.announcements.length
}, 3000)
}
}
}
</script>
<style>
.announcement-box {
height: 30px;
line-height: 30px;
overflow: hidden;
position: relative;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
结合后端数据的公告实现
<template>
<div v-if="announcements.length > 0" class="announcement-list">
<div v-for="(item, index) in announcements" :key="index" class="announcement-item">
<span class="announcement-time">{{ item.time }}</span>
<span class="announcement-text">{{ item.content }}</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
announcements: []
}
},
async created() {
try {
const response = await this.$http.get('/api/announcements')
this.announcements = response.data
} catch (error) {
console.error('获取公告失败:', error)
}
}
}
</script>
<style>
.announcement-list {
border: 1px solid #eee;
border-radius: 4px;
padding: 10px;
}
.announcement-item {
padding: 8px 0;
border-bottom: 1px dashed #ddd;
}
.announcement-item:last-child {
border-bottom: none;
}
.announcement-time {
color: #999;
margin-right: 15px;
}
</style>
使用第三方库实现公告功能
可以安装 vue-notification 等插件快速实现:
npm install vue-notification
<template>
<button @click="showNotification">显示公告</button>
</template>
<script>
import Vue from 'vue'
import Notifications from 'vue-notification'
Vue.use(Notifications)
export default {
methods: {
showNotification() {
this.$notify({
title: '重要公告',
text: '系统将于明日凌晨进行维护',
type: 'warn',
duration: 5000
})
}
}
}
</script>
以上方法可根据实际需求选择或组合使用,实现不同风格的公告展示效果。







