广州网站建设=388元,福建住房城乡建设部网站,冬青街 做网站,跨境平台哪个最好做?在现代前端开发中#xff0c;添加一些视觉效果可以提升用户体验。其中#xff0c;打字机效果是一种常见且吸引人的效果#xff0c;可以用于展示动态文本。本文将介绍如何在 Vue 3 中实现打字机效果。 实现步骤
1. 创建自定义指令
我们首先创建一个自定义指令 v-typewriter… 在现代前端开发中添加一些视觉效果可以提升用户体验。其中打字机效果是一种常见且吸引人的效果可以用于展示动态文本。本文将介绍如何在 Vue 3 中实现打字机效果。 实现步骤
1. 创建自定义指令
我们首先创建一个自定义指令 v-typewriter用于实现打字机效果。这个指令将逐字显示绑定的文本内容。
const typeWriter ref(null);const typewriterDirective (el, binding) {const indexValue el.getAttribute(data-index);const delay 150; // 设置延迟时间默认150mslet i 0;typeWriter.value setInterval(() {if (binding?.value i binding.value.length) {if (textList.value textList.value[indexValue]) {textList.value[indexValue].typewriterText binding.value.charAt(i) || ;}i;} else {clearInterval(typeWriter.value);stop(textList.value[indexValue], indexValue, true);}}, delay);
};const vTypewriter {mounted(el, binding) {typewriterDirective(el, binding);}
};
2. 使用自定义指令
在 Vue 组件中使用自定义指令 v-typewriter。该指令会在元素挂载时自动触发逐字显示文本内容。
templatediv classleft-content mr-16el-scrollbar refscrollRef height100% classscrolldiv classflex mb-48 v-for(item, index) in textList :keyitem.updateKeydiv classuser-avatarimg v-ifitem.resultTts || item.library src/img/avatar.png alt /img v-else src/img/user_avatar.png alt //divdiv classml-12div classtime mb-11span v-ifitem.resultTts || item.library智能馆员{{ item.time }}/spanspan v-else读者{{ item.time }}/span/divdivdivclassanswer:classitem.resultTts || item.library ? libarary-bg : user-color div v-ifitem.resultTts || item.libraryvan-loading v-if!item.resultMessage typespinner color#1989fa /div v-ifitem.isStop item.stopText{{ item.stopText }}/divdivv-ifitem.resultTts !item.isStopv-typewriteritem.resultTts:data-indexindex{{ item.typewriterText }}/div/divdiv v-else{{ item.resultMessage }}/div/divdivv-if(!item.isStop item.resultTts) || !item.resultMessageclassstop-icon mt-18clickstop(item, index)停止生成/div/divBookListv-ifitem.dataList?.length item.isStop:data-listitem.dataList/BookList/div/div/el-scrollbar/div
/templatescript
import { ref } from vue;
import { useEventBus } from /hooks/useEventBus;const emits defineEmits([watchTypeWriter, handleStop]);const textList ref([]);
useEventBus(clearChatInfo, () {textList.value [];
});
useEventBus(changeAction, (message) {
// message其它组件传递的数据 clearInterval(typeWriter.value);if (!textList.value.length || !message.resultTts) {textList.value.push({time: ${dayjs().format(HH:mm:ss)},isStop: false, // 是否停止stopText: , // 打字机停止后的内容typewriterText: , // 动态展示打字机内容的文本updateKey: dayjs().valueOf(), // 每次增加一条数据的唯一key...message});return;}if (textList.value.length message.resultTts) {textList.value[textList.value.length - 1] {...textList.value[textList.value.length - 1],...message};}
});const stop (item, index, isFinish false) {if (!item.resultMessage) {item.isStop true;emits(handleStop);return;}if (item.isStop) {return;}const curText document.querySelector([data-index${index}]);item.isStop true;item.stopText curText?.innerText;
};
/scriptstyle scoped langscss
/* 自定义样式*/
/style