vue实现ai逐字输出
实现思路
通过Vue的响应式数据和定时器,结合字符串分割与逐字拼接,模拟AI逐字输出的效果。核心是利用setInterval逐步更新显示文本,并通过v-text或{{}}绑定到模板。
基础实现代码
<template>
<div>
<p>{{ displayedText }}</p>
</div>
</template>
<script>
export default {
data() {
return {
fullText: "这里是需要逐字输出的AI回答内容",
displayedText: "",
currentIndex: 0,
typingSpeed: 100 // 控制输出速度(毫秒)
};
},
mounted() {
this.startTyping();
},
methods: {
startTyping() {
const timer = setInterval(() => {
if (this.currentIndex < this.fullText.length) {
this.displayedText += this.fullText.charAt(this.currentIndex);
this.currentIndex++;
} else {
clearInterval(timer);
}
}, this.typingSpeed);
}
}
};
</script>
进阶优化版本
添加光标动画和中断逻辑,提升交互体验:
<template>
<div>
<p>
{{ displayedText }}
<span class="cursor" :class="{ blinking: isTyping }">|</span>
</p>
<button @click="stopTyping">停止输出</button>
</div>
</template>
<script>
export default {
data() {
return {
fullText: "进阶版:支持中断的逐字输出效果",
displayedText: "",
currentIndex: 0,
typingSpeed: 80,
isTyping: false,
timer: null
};
},
mounted() {
this.startTyping();
},
methods: {
startTyping() {
this.isTyping = true;
this.timer = setInterval(() => {
if (this.currentIndex < this.fullText.length) {
this.displayedText += this.fullText.charAt(this.currentIndex);
this.currentIndex++;
} else {
this.stopTyping();
}
}, this.typingSpeed);
},
stopTyping() {
clearInterval(this.timer);
this.isTyping = false;
}
}
};
</script>
<style>
.cursor {
color: #42b983;
font-weight: bold;
}
.blinking {
animation: blink 1s infinite;
}
@keyframes blink {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 1; }
}
</style>
动态内容处理
通过watch监听外部传入的内容变化,实现动态响应:
props: {
aiResponse: {
type: String,
required: true
}
},
watch: {
aiResponse(newVal) {
this.fullText = newVal;
this.displayedText = "";
this.currentIndex = 0;
this.stopTyping();
this.startTyping();
}
}
性能注意事项
- 组件销毁前清除定时器
beforeDestroy() { clearInterval(this.timer); } - 长文本分段处理避免界面卡顿
- 使用
requestAnimationFrame替代setInterval可获得更平滑的动画效果







