效果图如下
打字机气泡组件
<template>
<div class="row-4" v-show="msgShow">{{msgShow}}</div>
</template>
<script>
export default {
name: "chat",
props: {
msg: {
type: String,
default: ''
},
delaytime: {
type: Number,
default: 0
}
},
data() {
return {
msgShow: '',
timeoutDelay: null,
timeoutShow: null
}
},
methods: {
startTyping() {
let currentIndex = 0;
const typingSpeed = 100; // 打字速度,单位:毫秒
this.timeoutShow = setInterval(() => {
this.msgShow += this.msg[currentIndex];
currentIndex++;
if (currentIndex >= this.msg.length) {
clearInterval(this.timeoutShow);
}
}, typingSpeed);
},
},
mounted() {
this.timeoutDelay = setTimeout(()=>{
this.startTyping()
},this.delaytime)
},
beforeDestroy() {
if (this.timeoutDelay) {
clearTimeout(this.timeoutDelay)
}
if (this.timeoutShow) {
clearInterval(this.timeoutShow);
}
}
}
</script>
<style lang="scss" scoped>
.row-4{
margin: 40rpx auto;
width: auto;
color: #fff;
line-height: 1.5;
text-align: left;
position: relative;
background: #4EBF0D;
border-radius: 28rpx;
padding:28rpx;
font-size: 28rpx;
}
.row-4::after{
content: '';
position: absolute;
width: 0;
height: 0;
left: 20rpx;
top: -20rpx;
border-left: 10rpx solid transparent;
border-right: 10rpx solid transparent;
border-bottom: 20rpx solid #4EBF0D;
transform: skewX(50deg);
}
</style>
父组件使用样例
<chatBubble :msg="msg1"></chatBubble>
<chatBubble :msg="msg2" :delaytime="msg1.length*100"></chatBubble>