vue实现数组中的项随机显示的两种方法
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" con
·
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue实现数组中的项随机显示</title>
</head>
<style>
#app {
width: 600px;
margin: auto;
}
li {
list-style: none;
}
p {
display: inline-block;
margin: 0 3px;
text-align: center;
float: left;
}
</style>
<body>
<div id="app">
<button @click="handleClick">数组项随机显示</button>
<li v-for="user in userArr">
<p>{{user.name}}</p>
</li>
</div>
</body>
<script src="./vue.js"></script>
<script>
const vm = new Vue({
el: "#app",
data: {
userArr: [
{
id: 0,
name: "feifei"
},
{
id: 1,
name: "wanglan"
},
{
id: 2,
name: "xiaya"
},
{
id: 3,
name: "weiwei"
},
{
id: 4,
name: "anpei"
},
{
id: 5,
name: "lanlan"
}
]
},
methods: {
// 方法一
// handleClick(){
// this.userArr.sort(function(){
// return Math.random()-0.5
// })
// }
// 方法二
handleClick() {
function sortArr(val) {
for (let i = 0; i < val.length; i++) {
let res = Math.floor(Math.random() * val.length);
let tempArr = val[res]
val[res] = val[i]
val[i] = tempArr
// 如果不添加这一句,vue检测不到数组的变化,页面数据是不会发生改变的
val.splice(val.length)
}
return val;
}
sortArr(this.userArr)
console.log(this.userArr)
}
}
})
</script>
</html>
更多推荐
已为社区贡献3条内容
所有评论(0)