# 三.数据输出(文本打字)
前言
文本打字效果组件
# 1.目录结构
├── text-typer
│ ├── typer.vue
│ └── index.js
1
2
3
2
3
# 2.组件封装
- 源代码
<template>
<div class="text-type-writer">
<pre
class="text-type-writer-line"
v-for="(item, index) in content"
:key="index"
>
{{ item.typewriter }}
</pre>
</div>
</template>
<script>
export default {
name: "TextTyper",
props: {
tip: {
type: Boolean,
default: false,
},
text: {
type: String | Array,
default: "",
},
},
data() {
return {
content: Array.isArray(this.text)
? this.text.map((o) => ({
content: o,
typewriter: "",
index: 0,
visible: false,
timer: null,
}))
: [
{
content: this.text,
typewriter: "",
index: 0,
visible: false,
timer: null,
},
],
};
},
mounted() {
this.typingLine(this.content, 0);
},
methods: {
typingLine(data, index) {
data[index].visible = true;
if (data[index].index <= data[index].content.length) {
data[index].typewriter = data[index].content.slice(
0,
data[index].index++
);
data[index].timer = setTimeout(() => {
this.typingLine(data, index);
}, 50);
} else {
clearTimeout(data[index].timer);
data[index].visible = false;
this.typingLine(data, index + 1);
}
},
},
};
</script>
<style lang="less" scoped>
.text-type-writer {
width: auto;
padding: 10px;
border: 1px dashed red;
border-radius: 5px;
.text-type-writer-line {
line-height: 1.2;
font-size: 20px;
color: rgb(96, 109, 121);
white-space: pre-wrap;
word-wrap: break-word;
border: none;
background: none;
padding: 0;
margin: 0;
}
.text-type-writer-cursor {
width: 0px;
height: 100%;
border-left: 2px solid transparent;
animation: typing 3s steps(16) forwards, cursor 1s infinite;
-webkit-animation: typing 3s steps(16) forwards, cursor 1s infinite;
}
}
/* animation */
@keyframes typing {
from {
width: 100%;
}
to {
width: 0;
}
}
@keyframes cursor {
50% {
border-color: #5e7ce0;
}
}
@-webkit-keyframes typing {
from {
width: 100%;
}
to {
width: 0;
}
}
@-webkit-keyframes cursor {
50% {
border-color: #5e7ce0;
}
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# 3.使用案例
刷新
全屏/自适应
刷新
全屏/自适应