1

I was just working my way through the vue transitions, and I came across one thing I don't understand.

I want to display a list that keeps shuffling. For this I wrote the function shuffle(), which is called every 2000ms. At the end of the function, I assign the shuffled new array to the variable this.items. However, the list in the DOM is not shuffled! If I reinitialise this.items as an empty array beforehand, the list is shuffled!

You can see this in the shuffle() function shown below. If I delete the line with this.items = [], the shuffle does not work.

I would be happy if someone could explain this to me.

Thats the html part of the code:

<transition-group name="flip-list" tag="ul">
          <li v-for="item in items" :key="item">
                    {{ item }}
          </li>
</transition-group>

Thats the js part:

<script>
export default {
  data () {
    return { items: [1, 2, 3, 4, 5, 6, 7, 8, 9] }
  },
  created () {
    setInterval(() => {
      this.shuffle()
    }, 2000)
  },
  methods: {
    shuffle () {
      const result = this.items
      let currentIndex = result.length
      let randomIndex

      // While there remain elements to shuffle...
      while (currentIndex !== 0) {
        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex)
        currentIndex--

        // And swap it with the current element.
        [result[currentIndex], result[randomIndex]] = [
          result[randomIndex], result[currentIndex]]
      }
      this.items = []
      this.items = result
    }
  }
}

</script>
tony19
  • 125,647
  • 18
  • 229
  • 307
okinava
  • 43
  • 1
  • 7
  • 1
    Assuming you are using stable Nuxt 2 (and not Nuxt 3 which is in beta) and therefore Vue 2 - some limitations apply to an [array change detection](https://vuejs.org/v2/guide/reactivity.html#For-Arrays) – Michal Levý Oct 23 '21 at 13:35
  • Yes I use Nuxt 2! – okinava Oct 25 '21 at 10:03

0 Answers0