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>