1. 程式人生 > 其它 >uniapp 微信小程式自己封裝頭部標題欄

uniapp 微信小程式自己封裝頭部標題欄

一、首先要關閉原生導航欄 :在pages.json 中設定"navigationStyle":"custom"

二、在APP.vue中

onLaunch: function() {
   uni.getSystemInfo({
       success: function(e) {
       // #ifndef MP
          Vue.prototype.StatusBar = e.statusBarHeight;
              if (e.platform == 'android') {
                  Vue.prototype.CustomBar 
= e.statusBarHeight + 50; } else { Vue.prototype.CustomBar = e.statusBarHeight + 45; }; // #endif // #ifdef MP-WEIXIN Vue.prototype.StatusBar = e.statusBarHeight; let custom = wx.getMenuButtonBoundingClientRect(); Vue.prototype.Custom
= custom; Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight; // #endif // #ifdef MP-ALIPAY Vue.prototype.StatusBar = e.statusBarHeight; Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
// #endif } }) },

三、在components資料夾下新建檔案:cu-custom.vue

<template>
    <view>
        <view class="cu-custom" :style="[{height:CustomBar + 'px'}]">
            <view class="cu-bar fixed" :style="style" :class="[bgImage!=''?'none-bg text-white bg-img':'',bgColor]">
                <view class="action" @tap="BackPage" v-if="isBack">
                    <text class="cuIcon-back"></text>
                    <slot name="backText"></slot>
                </view>
                <view class="content">
                    <slot name="content"></slot>
                </view>
                <slot name="right"></slot>
            </view>
            <image :src="bgImage" class="postyle" :style="[{height:CustomBar + 'px'}]"></image>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                StatusBar: this.StatusBar,
                CustomBar: this.CustomBar
            };
        },
        name: 'cu-custom',
        computed: {
            style() {
                var StatusBar= this.StatusBar;
                var CustomBar= this.CustomBar;
                var style = `height:${CustomBar}px;padding-top:${StatusBar}px;`;
                return style
            }
        },
        props: {
            bgColor: {
                type: String,
                default: ''
            },
            isBack: {
                type: [Boolean, String],
                default: false
            },
            bgImage: {
                type: String,
                default: ''
            },
        },
        methods: {
            BackPage() {
                uni.navigateBack({
                    delta: 1
                });
            }
        }
    }
</script>

<style>
.postyle{
    position: fixed;
    width: 100%;
    top: 0rpx;
    left: 0rpx;
    z-index: 2;
}

</style>

四、將新建的元件在main.js中註冊一下,需要的頁面就可以直接引用啦

五、在需要的頁面引用

<cu-custom bgColor="green-org" class="colorWhite" :isBack="false">
    <block slot="backText"></block>
    <block class="info-ifo" slot="content">首頁</block>
</cu-custom>

好啦來看看效果吧