easy-typer-js icon indicating copy to clipboard operation
easy-typer-js copied to clipboard

很棒的插件,提供一个 Vue3 实现多行依次打印的Vue Use

Open hoythan opened this issue 9 months ago • 0 comments

// useText.js
import { reactive } from 'vue'
import EasyTyper from 'easy-typer-js'

export default function useText(texts, delay = 0, option = {}) {
	const objs = texts.map(() => {
		return reactive({
			output: '',
			isEnd: false,
			speed: 100,
			singleBack: false,
			sleep: 0,
			type: 'normal',
			backSpeed: 40,
			sentencePause: false,
			...option
		})
	})
	// 将 textsGroup 嵌套起来
	const run = () => {
		return new Promise((resolve) => {
			const runText = (index) => {
				let callback
				if (index + 1 === objs.length) {
					callback = resolve
				} else {
					callback = () => {
						setTimeout(() => {
							runText(index + 1)
						}, delay)
					}
				}
				if (index === objs.length) return
				const obj = objs[index]
				new EasyTyper(obj, texts[index], callback)
			}
			runText(0)
		})
	}
	return { run, texts: objs }
}

const { texts, run } = useText(['这是一封心意满满的婚礼邀请函', '收到这封邀请函的你们', '都是我们人生中最重要的部分', '在这样特殊的一天, 希望有你的见证与祝福'], 300)
onMounted(async () => {
	// 异步监听
	console.log('play')
	await run()
	console.log('end')
})
<div class="texts">
	<div class="text" v-for="(text, index) in texts" :key="index">{{ text.output }}</div>
</div>

hoythan avatar May 17 '24 14:05 hoythan