首页 > 解决方案 > 页面加载时 Vue.js 中元素的随机/随机顺序

问题描述

我正在尝试使用 Vuejs ref 属性来定位一些元素,以随机化每个页面加载的顺序。

我的数据在模板中呈现并在组件中处理:

<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>

我在这里想念什么?我如何在我的卡片元素 TIA 的每个页面加载上洗牌/随机顺序!

标签: javascriptarraysvue.jsdomref

解决方案


this.set呼叫缺少$before 。set如果没有$,它将导致set不是函数的运行时错误。

this.$set(this.team, i, this.team[randomIndex])
this.$set(this.team, randomIndex, temp)

也可以Vue.set使用;但由于set在可以访问 Vue 实例的函数中调用,所以$set会更受欢迎。

工作示例:

https://codesandbox.io/s/eager-cori-cu75f


推荐阅读