vue实现ai逐字输出
实现思路
在Vue中实现AI逐字输出效果,可以通过定时器逐步显示文本内容。核心逻辑是拆分字符串,按顺序逐个字符添加到显示变量中。
基础实现方法
安装Vue项目后,在组件中定义数据和方法:
data() {
return {
fullText: '这里是AI生成的完整文本内容',
displayedText: '',
currentIndex: 0
}
},
methods: {
typeWriter() {
if (this.currentIndex < this.fullText.length) {
this.displayedText += this.fullText.charAt(this.currentIndex)
this.currentIndex++
setTimeout(this.typeWriter, 100) // 调整速度
}
}
},
mounted() {
this.typeWriter()
}
模板部分:
<div>{{ displayedText }}</div>
优化版本
增加开始/暂停控制和动画效果:
data() {
return {
fullText: '优化后的逐字输出效果',
displayedText: '',
currentIndex: 0,
isTyping: false,
typingSpeed: 50,
timer: null
}
},
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
},
resetTyping() {
this.stopTyping()
this.displayedText = ''
this.currentIndex = 0
}
}
添加光标动画
CSS部分:
.type-cursor {
display: inline-block;
width: 2px;
height: 1em;
background: #000;
animation: blink 1s infinite;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
模板更新:
<div>
{{ displayedText }}<span class="type-cursor"></span>
</div>
<button @click="startTyping" :disabled="isTyping">开始</button>
<button @click="stopTyping" :disabled="!isTyping">暂停</button>
<button @click="resetTyping">重置</button>
支持异步获取文本
当文本需要从API获取时:
async fetchAndType() {
const response = await fetch('api/text-generate')
this.fullText = await response.text()
this.resetTyping()
this.startTyping()
}
性能优化建议
对于长文本内容,建议分块处理避免界面卡顿:
const CHUNK_SIZE = 50
processChunk() {
const end = Math.min(this.currentIndex + CHUNK_SIZE, this.fullText.length)
this.displayedText = this.fullText.substring(0, end)
this.currentIndex = end
if (this.currentIndex < this.fullText.length) {
requestAnimationFrame(() => {
this.processChunk()
})
}
}






