admin管理员组文章数量:1130349
效果:
聊天对话时,将文本内容逐字展示,类似打字机效果。
实现原理:
利用定时器,以一定频率更改展示的文本内容长度,直至全部文本展示完毕。
组件封装:typer.vue
<template>
<view class="text">{{ curText }}</view>
</template>
<script>
export default {
props: {
content: { // 文本内容
type: String,
required: true
},
speed: { // 打字的速度
type: Number,
default: 100
},
startIndex: { // 默认从哪个索引开始
type: Number,
default: 0
}
},
data() {
return {
curIndex: -1, // 当前展示文字下标
isPause: false, // 是否暂停打字
timer: null, // 打字定时器
}
},
computed: {
curText() {
return this.content.substring(0, this.curIndex)
}
},
watch: {
content(v) {
v && this.reset()
}
},
created() {
this.start()
},
methods: {
// 开始打字
start(){
this.curIndex = this.startIndex - 1
this.writeText()
},
// 暂停打字
pause() {
this.isPause = true
clearTimeout(this.timer)
this.$emit('pause')
},
// 继续打字
continue(){
this.isPause = false
this.writeText()
},
// 重新打字
reset(){
this.isPause = false
clearTimeout(this.timer)
this.start()
},
// 打字效果实现
writeText() {
this.curIndex++
if (this.curIndex > this.content.length) {
this.isPause = true
this.$emit('finish')
}
if (!this.isPause) {
this.timer = setTimeout(this.writeText, this.speed)
}
}
}
}
</script>
<style lang="scss" scoped>
.text {
font-size: 30rpx;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #3A4354;
line-height: 42rpx;
text-align: justify;
}
</style>
使用:
import Typer from '@/components/typer/index.vue' ```
<Typer :content="val"></Typer>
效果:
聊天对话时,将文本内容逐字展示,类似打字机效果。
实现原理:
利用定时器,以一定频率更改展示的文本内容长度,直至全部文本展示完毕。
组件封装:typer.vue
<template>
<view class="text">{{ curText }}</view>
</template>
<script>
export default {
props: {
content: { // 文本内容
type: String,
required: true
},
speed: { // 打字的速度
type: Number,
default: 100
},
startIndex: { // 默认从哪个索引开始
type: Number,
default: 0
}
},
data() {
return {
curIndex: -1, // 当前展示文字下标
isPause: false, // 是否暂停打字
timer: null, // 打字定时器
}
},
computed: {
curText() {
return this.content.substring(0, this.curIndex)
}
},
watch: {
content(v) {
v && this.reset()
}
},
created() {
this.start()
},
methods: {
// 开始打字
start(){
this.curIndex = this.startIndex - 1
this.writeText()
},
// 暂停打字
pause() {
this.isPause = true
clearTimeout(this.timer)
this.$emit('pause')
},
// 继续打字
continue(){
this.isPause = false
this.writeText()
},
// 重新打字
reset(){
this.isPause = false
clearTimeout(this.timer)
this.start()
},
// 打字效果实现
writeText() {
this.curIndex++
if (this.curIndex > this.content.length) {
this.isPause = true
this.$emit('finish')
}
if (!this.isPause) {
this.timer = setTimeout(this.writeText, this.speed)
}
}
}
}
</script>
<style lang="scss" scoped>
.text {
font-size: 30rpx;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #3A4354;
line-height: 42rpx;
text-align: justify;
}
</style>
使用:
import Typer from '@/components/typer/index.vue' ```
<Typer :content="val"></Typer>
版权声明:本文标题:uni-app小程序,ChatGPT打字机效果实现 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://it.en369.cn/jiaocheng/1763940642a2973388.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。


发表评论