TabBar.js
3.44 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// components/TabBar/TabBar.js
Component({
/**
* 组件的属性列表
*/
properties: {
tabList: {
type: Array,
observer: function (list) {
// 规范化 tab 列表为对象数组,支持字符串与多种字段名
this.normalizeTabList(list)
}
},
activeIndex: {
type: Number,
observer: function (n) {
console.log(this.data.tabIndex, 'activeIndex', n)
console.log(this.data.tabIndex != n)
if (this.data.tabIndex != n) {
this.setData({
tabIndex: this.data.activeIndex
})
this.setTab(this.data.tabIndex)
}
}
},
scroll: Boolean
},
/**
* 组件的初始数据
*/
data: {
tabIndex: 0,
tabItems: []
},
lifetimes: {
ready() {
// console.log('lifetimes',this.data.tabIndex);
// console.log('lifetimes',this.data.activeIndex);
// 确保首屏渲染有规范化后的 tabItems
this.normalizeTabList(this.data.tabList)
this.setTab(this.data.tabIndex)
let that = this
wx.$eventbus.on('page_show', n => {
!that.data.width && that.setTab(that.data.tabIndex)
})
}
},
/**
* 组件的方法列表
*/
methods: {
normalizeTabList(list = []) {
const tabItems = (list || []).map(item => {
let label = ''
let count
if (typeof item === 'string') {
label = item
} else if (item && typeof item === 'object') {
label =
item.text ??
item.label ??
item.name ??
item.title ??
item.brandName ??
''
if (item.firstBrandId == -1) {
label = item.firstBrandName
}
count = item.count
} else {
label = ''
}
return { label, count, _raw: item }
})
this.setData({ tabItems })
},
change(e) {
let { index } = e.currentTarget.dataset
this.setTab(index)
},
setTab(index = 0) {
let { tabIndex } = this.data
wx.$util.getViewInfo(
`#tab-${tabIndex}`,
old => {
let oldLeft = old.left
let oldWidth = old.width
wx.$util.getViewInfo(
`#tab-${index}`,
res => {
let { left, width } = res
if (tabIndex != index) {
let readyLeft = oldLeft > left ? left : oldLeft
let readyWidth =
oldLeft > left ? oldLeft - left : left - oldLeft
this.setData({
activeStyle: `width: var(--fontSize64);background-color:#347BFF;border-radius:3rpx;left:${readyLeft + readyWidth / 2
}px;transition: all .1s;`
})
}
setTimeout(() => {
this.setData({
activeStyle: `width: var(--fontSize64);left:${left + (width - 32) / 2
}px;background-color:#347BFF;`,
tabIndex: index,
to: `to-${index}`,
width
})
const itemObj =
this.data.tabItems && this.data.tabItems[index]
? this.data.tabItems[index]._raw ??
this.data.tabItems[index]
: undefined
this.triggerEvent('click', { index, item: itemObj })
}, 100)
},
this
)
},
this
)
}
}
})