前端文字逐字显示
場景,是AI gpt问答的时候,希望答案出现的时候逐字出现,而不是隐藏了,等全部返回之后再出现:
场景代码:是用数组去接受列表,然后v-for去显示的
需求:如何实现,先显示用户的问题,然后逐字显示GPT的答案
实现:js 实现逐字显示、延时函数模拟对话
<template>
<div class="chat-gpt">
<div id="chat-dialog" class="chat-dialog" ref="chatDialogRef">
<div id="chat-list" class="chat-list" ref="chatListRef">
<div v-for="(item, index) in chatList" :key="index">
<img
v-if="item.status && index % 2 == 0"
src="../../public/img/speak1.gif"
alt=""
/>
<div :class="index % 2 == 0 ? 'odd' : 'even'">{{ item.content }}</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
textCount: 0,
timer: null,
chatBaseList: [
"以今日5辆满电无人车,运输5小时能运完50吨货物的标准,已知每辆无人车运输1小时耗电10%,运输效率是多少,每辆无人车耗电多少?花费多长时间?",
"运输效率:50吨/5小时=10顿/小时,每辆无人车耗电:10%×5小时=50%,需花费5小时。",
"以现有运输效率前提下,再增加5辆无人运输车,完成共计150吨物资的运输任务,整体效率会提高到多少?每辆无人车耗电又是多少?共花费多长时间?",
"增加到10辆无人车,完成共计150吨物资运输任务,整体效率会提高到15顿/小时,每辆无人车耗电百分比是15%。运完150吨的话,总共要耗用1.5小时。",
"我来想想是否确认执行此调配操作?",
"您好,请您慎重考虑。我们将根据您的确认来决定是否执行此调配操作。",
"是"
],
chatList: []
};
},
mounted() {
this.initGPT();
},
methods: {
// 延时函数
sleep(delaytime = 10000) {
return new Promise(resolve => setTimeout(resolve, delaytime));
},
// 同步遍历,自定义延时时间
async delayDo(
iterList,
callback = data => console.log(`数据:${data}`),
delaytimeList
) {
let len = iterList.length;
for (let i = 0; i < len; i++) {
callback(iterList[i], i);
await this.sleep(delaytimeList[i]);
}
},
// 逐字显示内容
getChatContent(text, index) {
this.timer = setInterval(() => {
this.textCount++;
if (this.textCount == text.length + 1) {
this.textCount = 0;
this.chatList.splice(index, 1, { content: text, status: false });
clearInterval(this.timer);
return;
}
// 取字符串子串
let nowStr = text.substring(0, this.textCount);
this.chatList.splice(index, 1, { content: nowStr, status: true });
}, 200);
},
// 点击开始聊天
initGPT() {
// const delaytimeList = [11000, 8000, 6000, 15000, 4000];
const delaytimeList = [16000, 11000, 16000, 16000, 5000, 7000];
this.delayDo(
this.chatBaseList,
(item, i) => {
this.getChatContent(item, i);
},
delaytimeList
);
}
}
};
</script>
<style lang="scss" scoped>
.chat-gpt {
width: 33rem;
height: 43rem;
.chat-dialog {
position: relative;
height: 43rem;
background: 0/33rem url("../../public/img/chat-bg.png") no-repeat;
overflow: hidden;
.close-icon {
position: absolute;
top: 1rem;
right: 1rem;
width: 3.4rem;
height: 3.4rem;
img {
width: 100%;
height: 100%;
}
}
.chat-list {
display: flex;
flex-direction: column;
width: 90%;
margin: 0 auto;
margin-top: 2rem;
overflow: auto;
>div {
display: flex;
margin-top: 1rem;
>div {
max-width: 19rem;
padding: 0.6rem;
opacity: 0.8;
font-size: 0.9rem;
font-family: FZLanTingHei-L-GBK;
font-weight: 400;
color: #c5e7ff;
text-align: start;
}
.odd {
align-self: flex-start;
background: #435e6f;
border-radius: 0px 16px 16px 16px;
}
.even {
align-self: flex-end;
background: #31b8c8;
border-radius: 16px 0px 16px 16px;
}
img {
width: 2rem;
height: 2rem;
margin-right: 1rem;
}
}
>div:nth-of-type(odd) {
align-self: flex-start;
}
>div:nth-of-type(even) {
align-self: flex-end;
}
}
}
.chat-tips {
display: flex;
height: 5.82rem;
margin-top: 1rem;
.gpt-icon {
height: 100%;
img {
height: 100%;
}
}
}
}
</style><template>
<div>
<span>{{ showText }}</span>
</div>
</template>
<script>
export default {
data() {
return {
timer: null, //settimeout
showText: "",
};
},
mounted() {
this.appear(
"俄乌局势发生变化?泽连斯基点名批评西方国家,喊话普京坐下来谈。"
);
},
methods: {
appear(content) {
const _this = this;
this.showText = "";
clearTimeout(this.timer);
var speed = 50; //设置定时的速度 越来越快
var count = 1;
function changeContent() {
_this.showText = content.substring(0, count); //截取字符串
count++;
if (count != content.length + 1) {
speed -= 1;
if (speed < 5) speed = 5;
_this.timer = setTimeout(changeContent, speed);
}
}
changeContent();
},
},
};
</script><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>无用:https://www.nuomiphp.com/github/zh/600bfa8f4f34c64e0170449d.html
无用:https://github.com/Orlandster/vue-typed-js
无用:https://mattboldt.com/demos/typed-js/
无用:https://github.com/Orlandster/vue-typed-js
可参考:https://blog.csdn.net/weixin_41000111/article/details/78725784
可参考:https://wenku.csdn.net/answer/2if1iqkez1
尝试ing:https://blog.csdn.net/weixin_43997331/article/details/135376110?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-135376110-blog-124999549.235%5Ev43%5Econtrol&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-135376110-blog-124999549.235%5Ev43%5Econtrol&utm_relevant_index=2
最终实现:
<section class="banner">
<section
class="p3"
v-if="item.type === 'ai' && dialogueList.length - 1 === index"
>
<span>{{ latestAiMsg }}</span>
</section>const latestAiMsg = ref<string>('')
const tempStrForLatestMsg = ref<string>('')const printCharacter = (
latestAiMsg: Ref<UnwrapRef<string>>,
tempStrForLatestMsg: Ref<UnwrapRef<string>>
) => {
if (latestAiMsg.value.length >= tempStrForLatestMsg.value.length) {
return
} else {
// latestAiMsg仍然比tempStrForLatestMsg短,进入下一次等待和递归
setTimeout(() => {
latestAiMsg.value += tempStrForLatestMsg.value.charAt(
latestAiMsg.value.length
)
printCharacter(latestAiMsg, tempStrForLatestMsg)
}, 20)
}
}
// function callback(timestamp: number) {
// if (!lastTime) lastTime = timestamp // 初始化 lastTime
// const progress = timestamp - lastTime // 计算距离上次调用的时间差
//
// if (progress >= 1000) {
// console.log('这段代码每秒执行一次')
// lastTime = timestamp // 更新 lastTime
// }
//
// requestAnimationFrame(callback) // 继续请求下一个动画帧
// }
watch(dialogueList.value, (nv) => {
if (nv.length === chatLen.value) {
return
}
latestAiMsg.value = ''
tempStrForLatestMsg.value = ''
let newMsg = nv.slice(-1)[0]
if (newMsg.type === 'ai') {
tempStrForLatestMsg.value = newMsg.content
printCharacter(latestAiMsg, tempStrForLatestMsg)
chatLen.value = nv.length
}
})