我正在尝试每2秒将a添加到字符串char中,但是它没有用,在控制台中没有错误 Vue

问题描述

我知道任务非常简单。但是我不明白为什么它不起作用。 这是我实现方式下方的代码,据我检查function checkEmptyString(item){ if (item.trim().length > 0) return false; else return true; }; function checkIfArrayContainsEmptyString(array) { const containsEmptyString = array.some(checkEmptyString); return containsEmptyString; }; console.log(checkIfArrayContainsEmptyString(["","hey","","this","is","my","solution"])) // *returns true* console.log(checkIfArrayContainsEmptyString(["yay","it","works"])) // *returns false*,这部分没有错误,只是连接循环和setTimer有问题。有人看到错误了吗?

this.showStr += this.mainStr.charat(i)

解决方法

您的错误是您一次设置了所有计时器。您需要设置不同的计时器来按时间间隔间隔调用函数,如下所示:

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版本(用于虚拟人):

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>

,

抱歉,我发布了错误的代码。这是无效的代码

<template>
    <p>{{ showStr }}</p>
</template>

<script>
    export default {
        name: "GreetingTitle.vue",data(){
          return {
            mainStr: "Hello,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>