<template>
<div class="chat">
<div class="chat-bubble" v-for="(message, index) in messages" :key="index">
<div>{{ message.content }}</div>
<span v-if="showTyping && index === messages.length - 1">{{ typing }}</span>
</div>
</div>
</template>
<script>
export default {
name: 'Chat',
data() {
return {
messages: [],
typing: '',
showTyping: false,
intervalId: null
}
},
created() {
this.addMessage({
content:
`
为什么如此?因为在青春时代,生活充满了奇特而辛酸的不可思议的事。
Why is this so? Because in youth, life is filled with strange and poignant incredible things.
`
})
},
methods: {
addMessage(message) {
this.messages.push({ ...message, content: '' })
let i = 0
const msgLength = message.content.length
const typingDelay = Math.floor(Math.random() * 100) + 50 // 随机生成打字的延迟时间
const typeNextLetter = () => {
this.messages[this.messages.length - 1].content += message.content.charAt(i)
i++
if (i <= msgLength) {
setTimeout(typeNextLetter, typingDelay)
} else {
clearTimeout(this.intervalId)
this.showTyping = false
this.intervalId = setTimeout(() => {
this.addMessage({
content: '...'
})
}, Math.floor(Math.random() * 5000) + 1000)
}
}
clearTimeout(this.intervalId)
this.showTyping = true
this.intervalId = setTimeout(typeNextLetter, 500)
}
}
}
</script>
<style>
.chat {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
}
.chat-bubble {
margin: 5px;
padding: 10px;
border-radius: 10px;
background: #eee;
color: #333;
display: inline-block;
max-width: 70%;
word-break: break-word;
}
.chat-bubble:last-child {
margin-bottom: 20px;
}
</style>
【vue】仿chatGPT逐个打字效果
于 2023-05-03 17:29:00 首次发布