javascript - Vue.js:延迟地一次输出一个元素的数组内容

标签 javascript html arrays vue.js

在我的 Vue 实例的数据属性中,我有一个字符串数组。

data() {
  return { myArray: [] }
}

这个数组填充了一个句子的单词。例如:

['Hi', 'my', 'name', 'is', 'foo']

我想将句子输出到我模板中的段落标记,一次一个单词,中间有 1 秒的延迟,类似于提词器的工作方式:

[0 秒] - 你好

[1 秒] - 你好我的

[2 秒] - 你好我的名字

[3 秒] - 你好,我叫

[4 秒] - 你好,我叫 foo

感谢任何帮助。

最佳答案

您可以使用 setInterval 并在每次迭代时添加一个词:

new Vue({
  el: '#app',
  data: {
    array: ['Hi', 'my', 'name', 'is', 'foo'],
    string: '' // here your string will be stored
  },
  methods: {
    appendWords: function() {
      const it = this.array[Symbol.iterator](); // convenient for yeilding values
      const int = setInterval(() => { // time interval
        const next = it.next(); // next value 
        if (!next.done) { // done = true when the end of array reached
          this.string += ' ' + next.value; // concatenate word to the string
        } else {
          clearInterval(int); // when done - clear interval
        }
      }, 1000) // interval duration, 1s
    }
  },
  mounted() {
    this.appendWords(); // invoke function when ready
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <p>{{ string }}</p>
</div>

关于javascript - Vue.js:延迟地一次输出一个元素的数组内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44315056/

相关文章:

javascript - Youtube 嵌入 API 和外部 JS

javascript - 如何使用客户端 javascript 将外部/内部 css 样式转换为内联样式属性

html - 如何使图片中间和链接在同一行?

javascript - 遍历 JSON - 特殊方式

java - 打印具有 3D 数组字段的类

php - 在提交表单之前重新加载页面

javascript - JS : find lowest/highest number from array within a specific range

javascript - 如何使用 jQuery 遍历 JSON 数组

javascript - 通过动态创建的id动态选择div

php - IE8 图像问题