Collapse.vue
3.1 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<template>
<div class="collapse-com" :style="{ backgroundColor: backgroundColor }">
<slot></slot>
</div>
</template>
<script>
export default {
name: 'Collapse',
props: {
value: [String, Array, Number],
accordion: {
type: Boolean,
default: () => {
return false
}
},
backgroundColor: {
type: String,
default: '#f5f5f5'
}
},
data() {
return {
currentValue: this.value
}
},
mounted() {
this.setActive()
},
methods: {
setActive() {
// 为它下面的子元素都设置一个index值
// console.log("setActive");
const activeKey = this.getActiveKey()
this.$children.forEach((child, index) => {
const name = child.name || index.toString() // toString 1=>"1"整数转换成为字符串
child.isActive = activeKey.indexOf(name) > -1 // 给选中的元素赋值活跃状态
// console.log(child);
child.index = index
})
},
toggle(data) {
// console.log("toggle");
const name = data.name.toString() // 强行转换成为字符串
let newActivekey = []
if (this.accordion) {
// 如果是手风琴模式
if (!data.isActive) {
newActivekey.push(name)
}
} else {
let activeKey = this.getActiveKey()
const nameIndex = activeKey.indexOf(name)
if (data.isActive) {
// 如果当前是展开状态
if (nameIndex > -1) {
activeKey.splice(nameIndex, 1)
}
} else {
if (nameIndex < 0) {
activeKey.push(name)
}
}
newActivekey = activeKey
}
this.currentValue = newActivekey
// console.log(data);
this.$emit('input', newActivekey)
this.$emit('on-change', newActivekey)
},
getActiveKey() {
// 获取当前展开的元素,并且做成数组的形式 1 => ["1"]
let activeKey = this.currentValue || []
const accordion = this.accordion
if (!Array.isArray(activeKey)) {
// 判断 activeKey 是不是数组
activeKey = [activeKey] // 不是数组则让它变成数组
}
if (accordion && activeKey.length > 1) {
// 如果是手风琴模式,必定是只会有一个元素
activeKey = [activeKey[0]]
}
for (let i = 0; i < activeKey.length; i++) {
activeKey[i] = activeKey[i].toString()
}
return activeKey
}
},
watch: {
value(val) {
this.currentValue = val
},
currentValue() {
this.setActive()
}
}
}
</script>
<style lang="scss" scoped></style>