如何通过Vue.js每秒循环输出一个字符串数组

时间:2017-05-13 16:45:32

标签: javascript vue.js vue-component

让我们说这里有几个词:apple,bpple,cpple

我想将它们展示成循环

第二个1:苹果 然后第二个2:bpple 然后3:cpple 然后4:苹果 ...

比如每秒'<div>value</div>'动态更改值

我怎样才能实现这一目标?

2 个答案:

答案 0 :(得分:1)

据我了解您的问题,请尝试以下代码:

<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

答案 1 :(得分:0)

您可以使用remainder operator(modulo)循环遍历数组,如下例所示。

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>