在Vue实例的数据属性中,我有一个字符串数组。
data() {
return { myArray: [] }
}这个数组中充满了一个句子的单词。例如:
['Hi', 'my', 'name', 'is', 'foo']我想将句子输出到模板中的段落标记,每次一个单词,中间延迟1秒,类似于提词器的工作方式:
0秒-嗨
1秒-嗨
2秒-嗨我的名字
三秒-嗨我的名字是
4秒-嗨,我叫福
任何帮助都是非常感谢的。
发布于 2017-06-01 19:04:21
您可以使用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>
发布于 2017-06-01 19:04:28
代码
new Vue({
el:"#app",
data:{
base: ['Hi', 'my', 'name', 'is', 'foo'],
timed: []
},
mounted(){
this.base.forEach((item, i) => {
setTimeout(() => {
this.timed.push(`[${i} sec] - ${this.base.slice(0, i + 1).join(" ")}`)
}, i * 1000)
})
}
})模板
<div id="app">
<p v-for="time in timed">{{time}}</p>
</div>示例。
编辑
因此,为了好玩,我考虑了如何在javascript中制作一个提词器模拟。这是相当天真,但工作的时间,我已经投入了它。
new Vue({
el:"#app",
data:{
lines: [
'Hi, my name is Foo. I am a literal',
'programmer. This is a teleprompter',
'simulation. These lines should all',
'be about the same length. There are ',
'different strategies for making that',
'happen.'
],
show:[]
},
mounted(){
let currentIndex = 0
this.$el.addEventListener('animationend', () => {
this.show.push(this.lines[++currentIndex])
})
this.show.push(this.lines[0])
}
})@keyframes revealText {
0% {
width:0%;
}
100% {
width:100%;
}
}
#app{
width: 500px;
margin: auto
}
h1 {
white-space:nowrap;
overflow: hidden;
animation: revealText 5s;
}<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<h1 v-for="line in show">{{line}}</h1>
</div>
https://stackoverflow.com/questions/44315056
复制相似问题