You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何在v-for循环里使用setTimeout实现字符逐字间隔显示

实现逻辑

你不需要在v-for循环中处理时间间隔,只需要按指定间隔往characterArray数组中逐个追加字符,依托Vue的响应式渲染能力,就能实现字符逐个显示的效果。

修改后的代码如下:

HTML 代码

<button @click="showCharacterArray">click me</button>
<p>
  <!-- 这里key使用索引,避免相同字符导致的渲染异常问题 -->
  <span v-for="(char, index) in characterArray" :key="index">{{char}}</span>
</p>

Vue 逻辑代码

export default {
  data() {
    return {
      Paragraph: "Includes The Plan, The Thought Process, Action, And Implementation. Planning Gives More Power Over The Future. Planning Is Deciding In Advance What To Do, How To Do It, When To Do It, And Who Should Do It. This Bridges The Gap From Where The Organization Is To Where It Wants To Be.",
      characterArray: [],
      charDelay: 50, // 字符显示间隔,单位为毫秒,可自行调整数值修改显示速度
      showTimer: null // 存储定时器ID,避免重复点击导致的显示混乱
    }
  },
  methods: {
    showCharacterArray() {
      // 先清空原有内容和已存在的定时器
      this.characterArray = []
      clearTimeout(this.showTimer)
      
      const allChars = this.Paragraph.split('')
      allChars.forEach((char, index) => {
        // 每个字符的延迟时间为索引 * 间隔,保证按顺序逐个显示
        this.showTimer = setTimeout(() => {
          this.characterArray.push(char)
        }, index * this.charDelay)
      })
    },
  },
  // 组件销毁时清除定时器,避免内存泄漏
  beforeDestroy() {
    clearTimeout(this.showTimer)
  }
}

注意事项

  1. 原代码存在变量大小写不一致的问题:data中定义的是characterArray,方法中赋值用了首字母大写的CharacterArray,会导致赋值失效,修改后的代码已修正该问题。
  2. 如果需要调整字符显示速度,直接修改charDelay的数值即可,数值越小显示速度越快。

内容的提问来源于stack exchange,提问作者Younoch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:18:00