vue实现逐字显示
实现逐字显示的基本思路
在Vue中实现逐字显示效果,可以通过动态更新文本内容的方式完成。核心逻辑是利用定时器逐步将目标字符串的字符拼接到显示变量上。
基础实现方法
定义一个响应式数据存储当前显示的文本,使用setInterval或递归setTimeout逐步添加字符:
<template>
<div>{{ displayedText }}</div>
</template>
<script>
export default {
data() {
return {
fullText: '这是要逐字显示的完整文本',
displayedText: '',
currentIndex: 0
}
},
mounted() {
this.typeWriter()
},
methods: {
typeWriter() {
if (this.currentIndex < this.fullText.length) {
this.displayedText += this.fullText.charAt(this.currentIndex)
this.currentIndex++
setTimeout(this.typeWriter, 100) // 调整时间间隔控制速度
}
}
}
}
</script>
使用CSS动画增强效果
可以添加光标闪烁效果增强视觉体验:
.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="cursor"></span>
</div>
封装为可复用组件
将功能封装为组件便于复用:
<template>
<div>
{{ displayedText }}<span v-if="isTyping" class="cursor"></span>
</div>
</template>
<script>
export default {
props: {
text: {
type: String,
required: true
},
speed: {
type: Number,
default: 100
}
},
data() {
return {
displayedText: '',
currentIndex: 0,
isTyping: true
}
},
mounted() {
this.startTyping()
},
methods: {
startTyping() {
if (this.currentIndex < this.text.length) {
this.displayedText += this.text.charAt(this.currentIndex)
this.currentIndex++
setTimeout(this.startTyping, this.speed)
} else {
this.isTyping = false
}
}
}
}
</script>
添加删除效果
实现先打字后删除的循环效果:
methods: {
startTyping() {
if (this.currentIndex < this.text.length) {
this.displayedText += this.text.charAt(this.currentIndex)
this.currentIndex++
setTimeout(this.startTyping, this.speed)
} else {
setTimeout(this.startDeleting, this.speed * 2)
}
},
startDeleting() {
if (this.displayedText.length > 0) {
this.displayedText = this.displayedText.substring(0, this.displayedText.length - 1)
setTimeout(this.startDeleting, this.speed / 2)
} else {
this.currentIndex = 0
setTimeout(this.startTyping, this.speed)
}
}
}
使用第三方库
考虑使用专门的字幕动画库如typeit获得更多特效:

import TypeIt from 'typeit'
mounted() {
new TypeIt(this.$refs.typeElement, {
strings: ['第一段文字', '第二段文字'],
speed: 100,
loop: true
}).go()
}






