一、代码
<template>
<van-barrage v-model="list" rows="1" duration="7000" :delay="delay" >
<div style="width: 80%; height: 36px"></div>
</van-barrage>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const props = defineProps({
numberSegment: {
type: Array,
default: function () {
return [139, 136, 137, 138, 139, 135, 183];
},
require: false,
},
});
const numberSegment = ref(props.numberSegment);
defineExpose({ numberSegment });
const defaultList = [];
const delay = 1;
const list = ref([...defaultList]);
// 添加一个标志来控制是否应该生成弹幕
const shouldGenerate = ref(true);
function generatePhoneNumber() {
if (!shouldGenerate.value) return;
let arr = numberSegment.value;
let i = Math.floor(Math.random() * numberSegment.value.length);
let randomStr = Math.floor(new Date().getTime() % 10000) * 100 + '0';
let num = arr[i] + '****' + randomStr.substring(0, 4) + '已领取';
list.value.push({ id: Math.random(), text: num });
}
setInterval(generatePhoneNumber, 2000);
// 添加事件监听器来处理页面的 visibilitychange 事件
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
// 页面不可见时,暂停弹幕生成
shouldGenerate.value = false;
} else {
// 页面可见时,恢复弹幕生成
shouldGenerate.value = true;
}
});
// 记得移除事件监听器
onUnmounted(() => {
document.removeEventListener('visibilitychange', generatePhoneNumber);
});
</script>
<script lang="ts">
export default {
name: 'Danmu',
};
</script>
现在切换到别的页面,第一条弹幕还是会有重叠现象