当前位置:首页 > VUE

vue实现ai逐字输出

2026-01-20 02:31:08VUE

实现思路

在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()
    })
  }
}

vue实现ai逐字输出

标签: vueai
分享给朋友:

相关文章

vue实现视窗

vue实现视窗

Vue 实现视窗功能 在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、响应式布局或创建自定义弹窗组件。以下是几种常见实现方式: 监听浏览器窗口大小变化 使用 Vue 的 mounted…

vue 实现toast

vue 实现toast

vue 实现 toast 的方法 在 Vue 中实现 Toast 提示功能可以通过多种方式,以下是几种常见的实现方法: 使用第三方库 Vue 生态中有许多成熟的 Toast 库,例如 vue-toa…

vue实现sso

vue实现sso

Vue 实现 SSO(单点登录)方案 单点登录(SSO)允许用户通过一次登录访问多个相关系统。以下是基于 Vue 的实现方案: 使用 OAuth2/OpenID Connect 协议 OAuth2…

vue实现闪烁

vue实现闪烁

Vue实现元素闪烁效果 使用CSS动画实现 通过Vue绑定class结合CSS动画实现闪烁效果,代码简洁且性能较好。 <template> <div :class="{…

vue 实现视频

vue 实现视频

Vue 实现视频播放功能 使用 Vue 实现视频播放功能可以通过 HTML5 的 <video> 标签或第三方库(如 video.js)来实现。以下是两种常见的方法: 使用 HTML5…

vue实现定时

vue实现定时

Vue 实现定时功能的方法 使用 setInterval 和 clearInterval 在 Vue 中可以通过 setInterval 和 clearInterval 实现定时功能。在组件的 mou…