I am trying to target some elements with the Vuejs ref attribute to randomize the order on each page load.
My data is rendered in template and handled in the component:
<div class="team" >
<div class="team__card" ref="card" v-for="(member, index) in team"
:key="index">
<div v-for="(image, imageIndex) in member.image" :key="imageIndex">
<img :src="image" alt="Photo of team member" :key="imageIndex" />
</div>
<div class="team__card-content">
<p class="font-bold text-xl">{{ member.name }}</p>
<p class="font-bold text-gray-700">{{ member.title }}</p>
<p class="text-gray-700">{{ member.description }}</p>
</div>
</div>
</div>
<script>
export default {
name: 'Page Name',
data() {
return {
team: [
{
image: [require('url')],
name: 'Name',
title: 'Title',
description:'description.'
},
{
image: [require('url')],
name: 'Name',
title: 'Title',
description:'description.'
},
]
}
},
created() {
this.randomize()
},
methods: {
randomize() {
for (let i = this.team.length - 1; i > 0; i--) {
let randomIndex = Math.floor(Math.random() * i)
let temp = this.team[i]
this.set(this.team, i, this.team[randomIndex])
this.set(this.team, randomIndex, temp)
}
}
}
}
</script>
What am i missing here? How do i shuffle/randomize order on each page load of my card element TIA!
The this.set
call is missing a $
before set
. Without the $
, it will cause a runtime error where set
is not a function.
this.$set(this.team, i, this.team[randomIndex])
this.$set(this.team, randomIndex, temp)
Alternatively Vue.set
could be used; but since set
being called within a function where it has access to a Vue instance, $set
would be preferred.
Working example: