帮我用vue写一个逐字输出的效果
时间: 2024-05-08 21:19:53 浏览: 160
好的,以下是一个简单的逐字输出效果的Vue组件示例:
```
<template>
<div class="typewriter">
<span v-for="(char, index) in text" :key="index" v-bind:class="{ 'active': index <= currentIndex }">{{ char }}</span>
</div>
</template>
<script>
export default {
name: 'Typewriter',
props: {
text: {
type: String,
default: ''
},
speed: {
type: Number,
default: 100
}
},
data() {
return {
currentIndex: -1,
timer: null
};
},
mounted() {
this.startTyping();
},
methods: {
startTyping() {
this.timer = setInterval(() => {
this.currentIndex++;
if (this.currentIndex >= this.text.length) {
clearInterval(this.timer);
this.timer = null;
}
}, this.speed);
}
}
};
</script>
<style scoped>
.typewriter {
display: inline-block;
}
.typewriter .active {
display: inline-block;
opacity: 1;
animation: typing 0.5s steps(40, end), blink 0.5s step-end infinite;
}
@keyframes typing {
from {
width: 0;
}
to {
width: auto;
}
}
@keyframes blink {
from,
to {
border-color: transparent;
}
50% {
border-color: black;
}
}
</style>
```
你可以在父组件中使用此组件并传递需要逐字输出的文本以及输出速度。
```
<template>
<div>
<Typewriter :text="hello" :speed="100"></Typewriter>
</div>
</template>
<script>
import Typewriter from './Typewriter.vue';
export default {
name: 'App',
components: {
Typewriter
},
data() {
return {
hello: 'Hello, World!'
};
}
};
</script>
```
希望对你有帮助!
阅读全文
相关推荐

















