How to react data changes in vue component?

Viewed 31

I am trying to build a component that should update the string using setInterval.

Here is the code of the component.

<script>
export default {
  data() {
    return {
      offers: [
        '1!',
        '2!',
        '3!',
      ],
      current_index: 0,
      indexInterval: null,
    }
  },
  created() {
    this.updateToastIndex()
  },
  beforeDestroy() {
    clearInterval(this.indexInterval)
  },
  methods: {
    updateToastIndex() {
      const indexInterval = setInterval(() => {
        this.$nextTick(() => {
          if (this.current_index === 2) {
            this.current_index = 0
            console.log(this.offers[this.current_index], 'changedprev')
          } else {
            this.current_index = this.current_index + 1
            console.log(this.offers[this.current_index], 'changed')
          }
        })
      }, 1000)
      this.indexInterval = indexInterval
    },
  },
}
</script>
<template>
  <div>{{ offers[current_index] }}</div>
</template>

I can see the current_index in updateToastIndex function getting updated but current_index in template is not getting updated.

Please suggest some solution

0 Answers
Related