vue 实现实时弹幕
实现实时弹幕的Vue方案
核心思路
实时弹幕功能需要结合WebSocket或类似技术实现即时数据传输,通过Vue的响应式机制动态渲染弹幕内容。关键点在于弹幕队列管理、动画效果和性能优化。
技术实现
安装必要依赖
npm install socket.io-client # WebSocket通信
npm install lodash.throttle # 性能优化
WebSocket连接与数据接收
// utils/socket.js
import io from 'socket.io-client';
const socket = io('https://your-websocket-server');
export const initSocket = (callback) => {
socket.on('new_danmu', (data) => {
callback(data);
});
};
弹幕组件实现

<template>
<div class="danmu-container">
<div
v-for="(item, index) in activeDanmus"
:key="index"
:class="['danmu-item', `color-${item.colorType}`]"
:style="{
top: `${item.top}px`,
animationDuration: `${item.speed}s`
}">
{{ item.text }}
</div>
</div>
</template>
<script>
import { initSocket } from './utils/socket';
import throttle from 'lodash.throttle';
export default {
data() {
return {
allDanmus: [],
maxTracks: 5,
trackHeight: 40
};
},
computed: {
activeDanmus() {
return this.allDanmus.filter(d => !d.isExpired);
}
},
methods: {
addDanmu(text) {
const track = this.findAvailableTrack();
const newDanmu = {
text,
track,
top: track * this.trackHeight,
speed: 8 + Math.random() * 4,
colorType: Math.floor(Math.random() * 6),
isExpired: false
};
this.allDanmus.push(newDanmu);
setTimeout(() => {
newDanmu.isExpired = true;
}, newDanmu.speed * 1000);
},
findAvailableTrack() {
const occupied = new Set(
this.activeDanmus.map(d => d.track)
);
for (let i = 0; i < this.maxTracks; i++) {
if (!occupied.has(i)) return i;
}
return Math.floor(Math.random() * this.maxTracks);
}
},
mounted() {
initSocket(throttle(this.addDanmu, 200));
}
};
</script>
<style>
.danmu-container {
position: relative;
height: 200px;
overflow: hidden;
}
.danmu-item {
position: absolute;
white-space: nowrap;
animation: danmuMove linear;
font-size: 16px;
pointer-events: none;
}
@keyframes danmuMove {
from { transform: translateX(100%); }
to { transform: translateX(-100%); }
}
.color-0 { color: #ff4e4e; }
.color-1 { color: #fc8d4d; }
.color-2 { color: #f5e356; }
/* 更多颜色样式... */
</style>
性能优化建议
内存管理 定期清理过期弹幕数据,防止数组无限增长:
setInterval(() => {
this.allDanmus = this.allDanmus.filter(d => !d.isExpired);
}, 60000);
渲染优化 使用CSS will-change属性提升动画性能:

.danmu-item {
will-change: transform;
}
后端配合 Node.js示例实现WebSocket广播:
// server.js
const io = require('socket.io')(3000);
io.on('connection', (socket) => {
socket.on('send_danmu', (data) => {
io.emit('new_danmu', data);
});
});
扩展功能
弹幕交互增强 添加暂停/播放控制:
// 在data中添加
data() {
return {
isPaused: false
}
}
// 在style中添加
.danmu-item {
animation-play-state: var(--danmu-state, running);
}
// 在模板中添加控制按钮
<button @click="isPaused = !isPaused">
{{ isPaused ? '播放' : '暂停' }}
</button>
// 在computed中添加
computed: {
danmuStyle() {
return {
'--danmu-state': this.isPaused ? 'paused' : 'running'
};
}
}
弹幕过滤 实现敏感词过滤和频率限制:
addDanmu(text) {
if (this.hasSensitiveWords(text)) return;
if (this.isTooFrequent()) return;
// ...原有逻辑
}






