微信小程序自定义tab栏。
代码参考
<template>
<view>
<view v-if="!fixed" :style="containerStyle" />
<view
:class="$style['nav']"
:style="containerStyle"
>
<view
:class="$style['bar']"
:style="{height: `${statusBarHeight}px`}"
/>
<view
:class="$style['title']"
:style="{height: `${navHeight}px`}"
>
<!-- 设置的默认标题为图片形式,所以需要让文字的展示优先级高于图片 -->
<image
v-if="titleImg && !titleText"
:src="titleImg"
:style="iconStyle"
/>
<view
v-if="titleText"
:style="titleStyle"
>
{{titleText}}
</view>
</view>
</view>
</view>
</template>
<script lang="ts">
import Taro from '@tarojs/taro';
import {COMMON} from '@/config/static.config';
interface NavigateState {
statusBarHeight: number;
navHeight: number;
containerStyle: Record<string, string>;
iconStyle: Record<string, string>;
titleStyle: Record<string, string>;
}
export default {
props: {
fixed: {
type: Boolean,
default: false,
},
background: {
type: String,
default: '#fff'
},
titleText: {
type: String,
default: '',
},
titleImg: {
type: String,
default: COMMON.NAVIGATE_TITLE,
},
fontSize: {
type: Number,
default: 16
},
color: {
type: String,
default: '#404040'
},
iconHeight: {
type: Number,
default: 24
},
iconWidth: {
type: Number,
default: 82
}
},
data(): NavigateState {
return {
statusBarHeight: 0,
navHeight: 0,
containerStyle: {},
iconStyle: {},
titleStyle: {},
};
},
created(): void {
this.setNavHeight();
this.setStyle();
},
methods: {
setNavHeight(): void {
const {statusBarHeight}: {statusBarHeight: number} = Taro.getSystemInfoSync();
const menuButton = Taro.getMenuButtonBoundingClientRect();
const {top, height}: {top: number; height: number} = menuButton;
const navHeight = (top - statusBarHeight) * 2 + height;
this.statusBarHeight = statusBarHeight;
this.navHeight = navHeight;
},
setStyle(): void {
this.containerStyle = {
'background-color': this.background,
'height': `${this.statusBarHeight + this.navHeight}px`,
'width': '100%',
};
this.iconStyle = {
width: `${this.iconWidth}px`,
height: `${this.iconHeight}px`,
};
this.titleStyle = {
'font-size': this.fontSize,
'color': this.color,
};
},
}
};
</script>
<style lang="scss" module>
.nav {
position: fixed;
top: 0;
width: 100%;
z-index: $zindex-fixed;
}
.title {
@include flex-center;
}
</style>