uniapp 小程序自定义导航栏nabbar

在使用uniapp写小程序时经常需要自定义导航条,Android系统和iOS系统导航条的高度是不同的,浏览借鉴了网上的一些文章的相关方法自己写了一个自定义nabbar的组件,通过slot可在父组件自定义导航栏的内容。

引入和使用nabbar组件

<template>
    <view>
        <view-nabbar>
            <slot-one>
               //自定义nabbar内容
            </slot-one>
        </view-nabbar>
    </view>
</template>

<script>
    import Nabbar from '@/components/nabbar.vue';
    export default {
        components: {
            'view-nabbar': Nabbar,
        }
    }
</script>

<style lang="scss">
</style>

nabbar组件

<template>
    <view class="nabbar" :style="{'height': statusBarHeight + barHeight + 'px'}">
         //手机状态栏
        <view class="status-bar" :style="{'height': statusBarHeight + 'px'}"></view> 
        //导航栏
        <view class="nabbar-box" :style="{ 'top': statusBarHeight+ 'px', 'heigth': barHeight + 'px' }">
            <view class="nabbar-cont" :style="{ width: barWidth +'px' }">
                <slot></slot>
            </view>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                statusBarHeight: 20,
                barHeight: 44,
                barWidth: null,
            };
        },
        mounted() {
            let that = this;
                        //通过uni自带api获取手机系统信息
            uni.getSystemInfo({
                success: function (res) {
                    // console.log(res)
                    that.statusBarHeight = res.statusBarHeight;      //手机状态栏高度
                    let isiOS = res.system.indexOf('iOS') > -1;    //是否为iOS系统
                    that.barHeight = !isiOS? 48: 44;    //导航栏高度,iOS:48,Android:44
                    that.barWidth = res.windowWidth - 87;     //nabbar可操作宽度 = 屏幕宽度 - 小程序右上角的胶囊宽度(87)
                }
            })
        },
    }
</script>

<style lang="scss">
    .nabbar{
        width: 100%;
    }
    .status-bar{
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        width: 100%;
        background-color: #FFFFFF;
        // height: var(--status-bar-height);
        z-index: 999;
    }
    .nabbar-box{
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        width: 100%;
        height: 88rpx;
        background-color: #ffffff;
        padding: 0 16rpx;
        z-index: 999;
        .nabbar-cont{
            height: 100%;
            display: flex;
            align-items: center;
        }
    }
</style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容