vue实现打字机
实现打字机效果的方法
在Vue中实现打字机效果可以通过动态更新文本内容的方式完成。以下是几种常见的实现方式:
使用setInterval实现基础打字机效果
<template>
<div>{{ displayText }}</div>
</template>
<script>
export default {
data() {
return {
fullText: '这里是需要逐字显示的内容',
displayText: '',
currentIndex: 0
}
},
mounted() {
this.typeWriter()
},
methods: {
typeWriter() {
if (this.currentIndex < this.fullText.length) {
this.displayText += this.fullText.charAt(this.currentIndex)
this.currentIndex++
setTimeout(this.typeWriter, 100) // 调整时间间隔控制打字速度
}
}
}
}
</script>
使用CSS动画增强视觉效果
可以结合CSS动画为打字机效果添加光标闪烁:
.typewriter {
border-right: 0.15em solid orange; /* 光标效果 */
white-space: nowrap;
overflow: hidden;
animation: blink-caret 0.75s step-end infinite;
}
@keyframes blink-caret {
from, to { border-color: transparent }
50% { border-color: orange; }
}
封装为可复用组件
将打字机效果封装为Vue组件:

<template>
<div class="typewriter" :style="{ '--speed': speed + 'ms' }">
{{ displayedText }}
</div>
</template>
<script>
export default {
props: {
text: {
type: String,
required: true
},
speed: {
type: Number,
default: 100
}
},
data() {
return {
displayedText: '',
currentIndex: 0
}
},
watch: {
text() {
this.resetAnimation()
}
},
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)
}
},
resetAnimation() {
this.displayedText = ''
this.currentIndex = 0
this.startTyping()
}
}
}
</script>
使用第三方库
对于更复杂的需求,可以考虑使用专门的字效果库:
-
typeit:功能丰富的打字效果库
npm install typeit -
在Vue中使用:
import TypeIt from 'typeit'
mounted() { new TypeIt('#element', { strings: ['第一段文字', '第二段文字'], speed: 100, loop: true }).go() }
### 添加删除效果
实现先打字后删除的循环效果:
```javascript
methods: {
typeWithDelete() {
if (this.currentIndex <= this.fullText.length) {
// 打字阶段
this.displayText = this.fullText.substring(0, this.currentIndex)
this.currentIndex++
setTimeout(this.typeWithDelete, this.speed)
} else if (this.currentIndex > this.fullText.length) {
// 删除阶段
this.displayText = this.fullText.substring(0,
this.fullText.length - (this.currentIndex - this.fullText.length))
this.currentIndex++
if (this.displayText === '') {
this.currentIndex = 0
}
setTimeout(this.typeWithDelete, this.speed/2) // 删除速度更快
}
}
}
以上方法可以根据具体需求进行调整和组合,实现不同风格的字效果。






