typescript编写微信小程序-自定义tab
配置
- 配置 app.json, 随便创建几个页面
{
"tabBar": {
"custom": true,
"color": "#7A7E83",
"selectedColor": "#3cc51f",
"borderStyle": "black",
"backgroundColor": "#ffffff",
"list": [
{
"pagePath": "pages/index/index",
"text": "首页"
},
{
"pagePath": "pages/test/index",
"text": "test"
},
{
"pagePath": "pages/tab/index",
"text": "tab"
}
]
},
...
"usingComponents": {
"van-tabbar": "@vant/weapp/tabbar/index",
"van-tabbar-item": "@vant/weapp/tabbar-item/index",
"van-icon": "@vant/weapp/icon/index"
}
}
tab组件
创建 custom-tab-bar 目录, 然后创建个组件
wxml
<van-tabbar active="{{ active }}" bind:change="onChange">
<van-tabbar-item wx:for="{{ list }}" wx:key="index" icon="{{ item.icon }}">
{{ item.text }}
</van-tabbar-item>
</van-tabbar>
index.ts
Component({
data: {
active: 0,
list: [
{
"url": "/pages/index/index",
"icon": "wap-home-o",
"text": "首页"
},
{
"url": "/pages/test/index",
"icon": "cluster-o",
"text": "test"
},
{
"url": "/pages/tab/index",
"icon": "setting-o",
"text": "tab"
},
]
},
methods: {
onChange(e) {
this.setData({active: e.detail});
wx.switchTab({
url: this.data.list[e.detail].url
});
},
init() {
const page = getCurrentPages().pop();
this.setData({
// @ts-ignore
active: this.data.list.findIndex(item => item.url === `/${page.route}`)
});
}
}
});
- active 标识当前激活的组件
- list 中的url必须和配置文件中的一样
- onChange 函数 点击时切换url
- init 函数 在页面中调用,改变激活的 active
页面
在页面的 onShow 生命周期调用 tab 组件的 init 方法
Page({
onShow: function () {
this.getTabBar().init();
},
})
源码: https://github.com/NikolasSky/ts-miniprogram/tree/master/ts-miniprogram-tab