TabBar.js
2.89 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
// components/TabBar/TabBar.js
Component({
/**
* 组件的属性列表
*/
properties: {
tabList: Array,
activeIndex: {
type: Number,
observer: function (n) {
if (this.data.tabIndex != n) {
this.setTab(n, { suppressClick: true })
}
}
},
scroll: Boolean,
/** 为 true 时 ready / page_show 触发的 setTab 不 emit click,避免子页首屏重复拉数 */
suppressInitialClick: {
type: Boolean,
value: false
}
},
/**
* 组件的初始数据
*/
data: {
tabIndex: 0
},
lifetimes: {
ready() {
this.setTab(this.data.tabIndex, { suppressClick: this.data.suppressInitialClick })
let that = this
wx.$eventbus.on('page_show', n => {
!that.data.width && that.setTab(that.data.tabIndex, { suppressClick: true })
})
}
},
/**
* 组件的方法列表
*/
methods: {
change(e) {
let {
index
} = e.currentTarget.dataset
this.setTab(index)
},
/**
* 切换内部 tab 下标并更新指示条样式。
* @param {number} [index=0]
* @param {{ suppressClick?: boolean }} [options] - suppressClick 为 true 时不 trigger click(首屏/ page_show 防重复拉数)
*/
setTab(index = 0, options = {}) {
const suppressClick = options.suppressClick === true
let {
tabIndex,
} = this.data
wx.$util.getViewInfo(`#tab-${tabIndex}`, old => {
if (!old) {
wx.$util.getViewInfo(`#tab-${index}`, res => {
if (!res) return
this.applyTabIndicator(index, res, suppressClick)
}, this)
return
}
let oldLeft = old.left
let oldWidth = old.width
wx.$util.getViewInfo(`#tab-${index}`, res => {
if (!res) return
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;`
})
}
this.applyTabIndicator(index, res, suppressClick)
}, this)
}, this)
},
/**
* @param {number} index
* @param {{ left: number, width: number }} res
* @param {boolean} suppressClick
*/
applyTabIndicator(index, res, suppressClick) {
const { left, width } = res
setTimeout(() => {
this.setData({
activeStyle: `width: var(--fontSize64);left:${left + (width - 32) / 2}px;background-color:#347BFF;`,
tabIndex: index,
to: `to-${index}`,
width
})
if (!suppressClick) {
this.triggerEvent('click', index)
}
}, 100)
}
}
})