javascript - 页面加载时 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 的每个页面加载上洗牌/随机顺序!
解决方案
this.set
呼叫缺少$
before 。set
如果没有$
,它将导致set
不是函数的运行时错误。
this.$set(this.team, i, this.team[randomIndex])
this.$set(this.team, randomIndex, temp)
也可以Vue.set
使用;但由于set
在可以访问 Vue 实例的函数中调用,所以$set
会更受欢迎。
工作示例:
推荐阅读
- javascript - 使用来自多个 PHP 页面的 AJAX 函数的填充变量更新 SQL 查询
- android - 如何在 Android/Kotlin 中关闭覆盖图像(setOnClickListener 不起作用)?
- alexa - 我可以使用“技能”一词来标记我的产品扩展吗?
- r - trim 参数在 mean() 函数中代表什么?
- bosch-iot-suite - 当事物被 Hub-Things Connection 更新时,事物侦听器不会被触发
- html - 为什么我的 CSS 边框没有出现在按钮周围的跨度上?
- css - 如何从外部css文件导入字体
- php - 拆分和分解重定向
- java - 在 Mongo 中插入 JSON
- xpath - 如果存在则选择元素的子元素,否则选择父元素