vue选项乱序实现
实现 Vue 选项乱序的方法
方法一:使用 v-for 和 sort 方法
在 Vue 模板中,可以通过 v-for 遍历数组,并使用 JavaScript 的 sort 方法结合随机数实现乱序。
<template>
<div>
<div v-for="item in shuffledItems" :key="item.id">
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '选项A' },
{ id: 2, text: '选项B' },
{ id: 3, text: '选项C' }
]
}
},
computed: {
shuffledItems() {
return [...this.items].sort(() => Math.random() - 0.5)
}
}
}
</script>
方法二:使用 Lodash 的 shuffle 方法
Lodash 提供了 shuffle 方法,可以更方便地实现数组乱序。
<template>
<div>
<div v-for="item in shuffledItems" :key="item.id">
{{ item.text }}
</div>
</div>
</template>
<script>
import { shuffle } from 'lodash'
export default {
data() {
return {
items: [
{ id: 1, text: '选项A' },
{ id: 2, text: '选项B' },
{ id: 3, text: '选项C' }
]
}
},
computed: {
shuffledItems() {
return shuffle(this.items)
}
}
}
</script>
方法三:使用 Fisher-Yates 洗牌算法
Fisher-Yates 算法是一种高效的乱序算法,适合对数组进行随机排序。
<template>
<div>
<div v-for="item in shuffledItems" :key="item.id">
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '选项A' },
{ id: 2, text: '选项B' },
{ id: 3, text: '选项C' }
]
}
},
computed: {
shuffledItems() {
const array = [...this.items]
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[array[i], array[j]] = [array[j], array[i]]
}
return array
}
}
}
</script>
方法四:在 created 钩子中初始化乱序数组
可以在组件的 created 钩子中对数组进行乱序,避免每次计算属性重新计算。
<template>
<div>
<div v-for="item in shuffledItems" :key="item.id">
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '选项A' },
{ id: 2, text: '选项B' },
{ id: 3, text: '选项C' }
],
shuffledItems: []
}
},
created() {
this.shuffledItems = [...this.items].sort(() => Math.random() - 0.5)
}
}
</script>
注意事项
- 性能考虑:如果数组较大,建议使用 Fisher-Yates 算法或 Lodash 的
shuffle方法,性能更优。 - 唯一键:确保
v-for中的:key使用唯一标识符,避免渲染问题。 - 响应式更新:如果数组需要动态更新,建议使用计算属性或方法,确保乱序效果实时生效。







