[英]Vue.js proper random ordering of v-for loop
有一个我想以随机顺序输出的列表。
我通过计算属性实现了这一点:
<div id="app">
<ul>
<li v-for="list in randomList" >
{{ list.text }}
</li>
</ul>
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
lists:[
{text:'js',value:'one'},
{text:'css',value:'two'},
{text:'html',value:'three'}
]
},
computed: {
randomList: function(){
return this.lists.sort(function(){return 0.5 - Math.random()});
}
}
});
</script>
但是,如果我有多个列表,我想通过应用方法或过滤器来简化此过程?
我尝试了没有成功的方法:
<div id="app">
<ul>
<li v-for="list in randomList(lists)" >
{{ list.text }}
</li>
</ul>
<ul>
<li v-for="name in randomList(names)" >
{{ name.text }}
</li>
</ul>
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
lists:[
{text:'js',value:'one'},
{text:'css',value:'two'},
{text:'html',value:'three'}
],
names:[
{text:'mary',value:'one'},
{text:'css',value:'two'},
{text:'html',value:'three'}
]
},
methods: {
randomList: function(rand){
return this.rand.sort(function(){return 0.5 - Math.random()});
}
}
});
</script>
您的代码有几个小错误,一个错误在您的方法中: randomList
,您正在使用this.rand
,其中rand
作为参数传递,因此您只需要通过rand
访问它,使用this.rand
它将查看 vue实例数据,并会给出以下错误:
类型错误:this.rand 未定义[了解更多]
在此处查看工作小提琴
代码:
methods: {
randomList: function(rand){
return rand.sort(function(){return 0.5 - Math.random()});
}
}
这里有一个错字: el:'#vapp',
=> 这应该是el:'#app',
列表(数组)需要使用 javascript 随机化,它与Vue.js或v-for
无关。
你的方法似乎是正确的。 我还将创建一种方法来随机化数组项,例如randomList(myList)
并直接在v-for
使用它。
但是,不是使用带有随机真/假返回值的排序函数,而是有一个更好的随机化数组实现: How to randomize (shuffle) a JavaScript array?
如果您查看使用sort()
进行随机化的第三个答案(类似于您的尝试),您就会知道这是一种不正确的方法。 (在评论中解释)
最重要的答案有正确的方法,您可以将其插入您的randomList()
方法。 以下是您的操作方法(类似于该问题中已接受的答案,但使用了新数组,而不更改原始列表):
methods: {
randomList: function(array){
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
var myRandomizedList;
// Clone the original array into myRandomizedList (shallow copy of array)
myRandomizedList = array.slice(0)
// Randomize elements within the myRandomizedList - the shallow copy of original array
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = myRandomizedList[currentIndex];
myRandomizedList[currentIndex] = myRandomizedList[randomIndex];
myRandomizedList[randomIndex] = temporaryValue;
}
// Return the new array that has been randomized
return myRandomizedList;
}
}
请注意:我没有测试上述内容。 它只是最流行的答案的复制粘贴,作为方法包含在您的 Vue 组件中,在为随机化克隆数组进行了必要的更改之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.