[英]I'm trying adding a to a string a char every 2 seconds, but it diesn't work, no errors in a console. Vue
I know task is super simple.我知道任务非常简单。 But I do not why it's not working.
但我不知道为什么它不起作用。 Here is a code below how I implemented, as far as I checked
this.showStr += this.mainStr.charAt(i)
there is no mistake in this part is just something wrong with connection loop and setTimer.这是我如何实现的代码,据我检查
this.showStr += this.mainStr.charAt(i)
这部分没有错误,只是连接循环和 setTimer 有问题。 Does anybody see an error?有人看到错误吗?
data(){
return {
mainStr: "Hello, my name is Eldar and I'm web-developer",
showStr: ''
}
},
methods:{
showString() {
for (let i = 0; i < this.mainStr.length; ++i) {
this.delay(i);
}
},
delay(i){
function delay() {
setTimeout(() => {
this.showStr += this.mainStr.charAt(i)
}, 2000)
}
}
},
mounted(){
this.showString();
}
Ohh I'm sorry I published the wrong code.哦,对不起,我发布了错误的代码。 Here is a code which doesnt work
这是一个不起作用的代码
<template>
<p>{{ showStr }}</p>
</template>
<script>
export default {
name: "GreetingTitle.vue",
data(){
return {
mainStr: "Hello, my name is Eldar and I'm web-developer",
showStr: ''
}
},
methods:{
showString() {
for (let i = 0; i < this.mainStr.length; ++i) {
this.delay(i);
}
},
delay(i){
setTimeout(() => {
this.showStr += this.mainStr.charAt(i)
}, 2000)
}
},
mounted(){
this.showString();
}
}
</script>
Your mistake is that you set all timers in one time.您的错误是您一次性设置了所有计时器。 You need to set different timers for calling your function time by time with interval, like that:
您需要设置不同的计时器以按时间间隔调用 function,如下所示:
const mainStr = "Hello, my name is Eldar and I'm web-developer"; let showStr = ''; for (let i = 0; i < mainStr.length; ++i) { delay(i); } function delay(i){ setTimeout(() => { showStr += mainStr.charAt(i) console.log(showStr); }, 300 * i) }
UP: Vue version (for dummies): UP:Vue 版本(用于傻瓜):
new Vue({ name: "GreetingTitle.vue", data(){ return { mainStr: "Hello, my name is Eldar and I'm web-developer", showStr: '' } }, methods:{ showString() { for (let i = 0; i < this.mainStr.length; ++i) { this.delay(i); } }, delay(i){ setTimeout(() => { this.showStr += this.mainStr.charAt(i) }, 300 * i) } }, mounted(){ this.showString(); } }).$mount('#container');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id='container'> <p>{{ showStr }}</p> </div>
Ohh I'm sorry I published the wrong code.哦,对不起,我发布了错误的代码。 Here is a code which doesnt work
这是一个不起作用的代码
<template>
<p>{{ showStr }}</p>
</template>
<script>
export default {
name: "GreetingTitle.vue",
data(){
return {
mainStr: "Hello, my name is Eldar and I'm web-developer",
showStr: ''
}
},
methods:{
showString() {
for (let i = 0; i < this.mainStr.length; ++i) {
this.delay(i);
}
},
delay(i){
setTimeout(() => {
this.showStr += this.mainStr.charAt(i)
}, 2000)
}
},
mounted(){
this.showString();
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.