在Vue中我们开发组件基本上都是写一个.vue文件,在里面进行组件逻辑代码的编写。还可以在.ts文件中使用render函数生成组件。最近在项目中使用render函数封装打字机效果组件。
1. typeit 介绍
typeit是一款轻量级打字机特效插件。该打印机特效可以设置打字速度,是否显示光标,是否换行和延迟时间等属性,它可以打印单行文本和多行文本,并具有可缩放、响应式等特点。
2. 安装typeit
pnpm add typeit
3. 创建组件目录
4. 编写代码
index.ts
import TypeIt from 'typeit'
export default defineComponent({
name: 'TypeIt',
props: {
/** 打字速度,以每一步之间的毫秒数为单位 */
speed: {
type: Number,
default: 200,
},
values: {
type: Array,
defalut: [],
},
className: {
type: String,
default: 'type-it',
},
cursor: {
type: Boolean,
default: true,
},
},
render() {
return h(
'span',
{
class: this.className,
},
{
default: () => [],
},
)
},
mounted() {
new (TypeIt as any)(`.${this.className}`, {
strings: this.values,
speed: this.speed,
cursor: this.cursor,
}).go()
},
})
5. 使用
<template>
<h2 class="outline-none">
<TypeIt :values="[title]" :cursor="false" :speed="150" />
</h2>
</template>
<script>
import TypeIt from '@/components/typeit'
let title: string = 'pureadmin'
</script>