如何通过Vue.js每秒循环输出一个字符串数组
How to output an array of string circularly every second through Vue.js
假设这里有几个词:apple、bpple、cpple
我要循环展示它们
秒1:apple
然后是第二个 2:bpple
然后 3:cpple
然后 4:apple
...
喜欢每秒动态更改 '<div>value</div>'
中的值
我怎样才能做到这一点?
您可以使用 remainder operator(取模)循环遍历数组,如我在以下示例中所示。
new Vue({
el: '#demo',
data: {
array: ['apple', 'bpple', 'cpple'],
counter: 0,
index: 0,
value: 'apple',
interval: 0
},
methods: {
start() {
this.stop();
this.interval = setInterval(() => {
this.index = ++this.counter % this.array.length;
this.value = this.array[this.index];
}, 1000);
},
stop() {
clearInterval(this.interval);
}
}
});
<script src="https://unpkg.com/vue"></script>
<div id="demo">
<div>counter: {{counter}} / index: {{index}} / value: {{value}}</div>
<button @click="start()">start</button>
<button @click="stop()">stop</button>
</div>
据我了解你的问题,试试这个代码:
<div id="demo">
<h2>{{myArray}}</h2>
<h3>{{arrayItem}}</h3>
<br>
<button @click="startCircular()">start</button>
</div>
javascript
var demo = new Vue({
el: '#demo',
data: {
myArray:['apple','bpple','cpple'],
arrayItem: ''
},
methods:{
startCircular(){
var i = 0; // the index of the current item to show
vm = this;
setInterval(function() { // setInterval makes it run repeatedly
vm.arrayItem = vm.myArray[i++];
if (i == vm.myArray.length) i = 0; // reset to first element if you've reached the end
}, 1000);
}
}
})
看这里的演示jsFiddle
假设这里有几个词:apple、bpple、cpple
我要循环展示它们
秒1:apple 然后是第二个 2:bpple 然后 3:cpple 然后 4:apple ...
喜欢每秒动态更改 '<div>value</div>'
中的值
我怎样才能做到这一点?
您可以使用 remainder operator(取模)循环遍历数组,如我在以下示例中所示。
new Vue({
el: '#demo',
data: {
array: ['apple', 'bpple', 'cpple'],
counter: 0,
index: 0,
value: 'apple',
interval: 0
},
methods: {
start() {
this.stop();
this.interval = setInterval(() => {
this.index = ++this.counter % this.array.length;
this.value = this.array[this.index];
}, 1000);
},
stop() {
clearInterval(this.interval);
}
}
});
<script src="https://unpkg.com/vue"></script>
<div id="demo">
<div>counter: {{counter}} / index: {{index}} / value: {{value}}</div>
<button @click="start()">start</button>
<button @click="stop()">stop</button>
</div>
据我了解你的问题,试试这个代码:
<div id="demo">
<h2>{{myArray}}</h2>
<h3>{{arrayItem}}</h3>
<br>
<button @click="startCircular()">start</button>
</div>
javascript
var demo = new Vue({
el: '#demo',
data: {
myArray:['apple','bpple','cpple'],
arrayItem: ''
},
methods:{
startCircular(){
var i = 0; // the index of the current item to show
vm = this;
setInterval(function() { // setInterval makes it run repeatedly
vm.arrayItem = vm.myArray[i++];
if (i == vm.myArray.length) i = 0; // reset to first element if you've reached the end
}, 1000);
}
}
})
看这里的演示jsFiddle