在我的 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/