vue实现打字机
实现打字机效果的基本思路
在Vue中实现打字机效果,可以通过动态更新显示文本内容,模拟逐字打印的效果。核心是利用定时器逐步追加字符到显示字符串中。
基础实现方法
-
定义数据 在Vue组件的data中定义需要显示的完整文本和当前显示的文本:
data() { return { fullText: '这里是需要逐字显示的文字内容', displayedText: '', typingSpeed: 100 // 打字速度(毫秒/字符) } } -
创建打字函数 使用递归或循环方式逐步追加字符:
methods: { typeWriter() { if (this.displayedText.length < this.fullText.length) { this.displayedText = this.fullText.substring(0, this.displayedText.length + 1) setTimeout(this.typeWriter, this.typingSpeed) } } } -
调用函数 在mounted生命周期钩子中启动打字效果:
mounted() { this.typeWriter() }
进阶实现方案
-
添加光标闪烁效果 在模板中添加光标元素并设置CSS动画:
<div class="typewriter"> {{ displayedText }}<span class="cursor">|</span> </div>CSS样式:
.cursor { animation: blink 1s infinite; } @keyframes blink { 0%, 100% { opacity: 1; } 50% { opacity: 0; } } -
支持多行文本 将fullText改为数组,循环打字:

data() { return { lines: ['第一行文字', '第二行文字', '第三行文字'], currentLine: 0, displayedText: '' } }更新打字函数:
typeWriter() { if (this.currentLine < this.lines.length) { const currentLineText = this.lines[this.currentLine] if (this.displayedText.length < currentLineText.length) { this.displayedText = currentLineText.substring(0, this.displayedText.length + 1) setTimeout(this.typeWriter, this.typingSpeed) } else { setTimeout(() => { this.currentLine++ this.displayedText = '' this.typeWriter() }, 1000) // 行间延迟 } } }
使用第三方库
-
vue-typed-js 安装库:
npm install vue-typed-js使用示例:
import Vue from 'vue' import VueTypedJs from 'vue-typed-js' Vue.use(VueTypedJs)模板中使用:

<vue-typed-js :strings="['第一段文字', '第二段文字']" :loop="true"> <span class="typing"></span> </vue-typed-js> -
自定义指令实现 创建全局指令:
Vue.directive('typewriter', { inserted(el, binding) { const text = binding.value let i = 0 const speed = binding.arg || 100 function type() { if (i < text.length) { el.innerHTML += text.charAt(i) i++ setTimeout(type, speed) } } type() } })使用指令:
<div v-typewriter="'这里是指令实现的打字效果'" v-typewriter:50></div>
注意事项
-
性能优化 长时间打字效果可能消耗资源,使用前清除已有定时器:
beforeDestroy() { clearTimeout(this.typeTimer) } -
响应式设计 当文本内容变化时重置效果:
watch: { fullText() { this.displayedText = '' this.typeWriter() } } -
可访问性考虑 为屏幕阅读器添加aria属性:
<div aria-live="polite">{{ displayedText }}</div>






