:相信很多小伙伴使用v-for的时候都遇见过需要使用v-if来做判断的问题,这里给大家推荐使用计算属性提前为数据过滤
效果
- tomi23
- jimi23
- lami23
- momi23
<template>
<div>
<ul>
<li v-for="(item,index) in filterUser" :key="index">{{item.name+item.age}}</li>
</ul>
<button @click="randomHiddenUser">随机隐藏用户</button>
<button @click="cancelHiddenUser">撤销隐藏</button>
</div>
</template>
<script>
export default {
name: 'computeDemo',
data () {
return {
user: [
{
name: 'tomi',
age: 23
},
{
name: 'jimi',
age: 23
},
{
name: 'lami',
age: 23
},
{
name: 'momi',
age: 23
}
],
userQueue: []
}
},
computed: {
filterUser () {
return this.user.filter(item => item.visble !== false)
}
},
methods: {
cancelHiddenUser () {
const leg = this.userQueue.length
if (leg === 0) {
return
}
const index = this.userQueue.pop()
this.user = this.user.map((item, i) => {
if (index === i) {
item.visble = true
}
return item
})
},
randomHiddenUser () {
const hiddenUserindex = this.getUserIndex()
const leg = hiddenUserindex.length
if (leg === 0) {
return
}
const index = hiddenUserindex[Math.floor(Math.random() * leg)]
this.user = this.user.map((item, i) => {
if (index === i && item.visble !== false) {
item.visble = false
this.userQueue.push(i)
}
return item
})
},
getUserIndex () {
const arr = []
this.user.forEach((item, index) => {
item.visble !== false && (arr.push(index))
})
return arr
}
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81