uniapp开发微信小程序--自定义头部导航栏-灵析社区

Ned

1. 取消页面原生的导航栏(pages.json文件)

页面支持通过配置 navigationStyle为custom,或titleNView为false,来禁用原生导航栏

{
"path": "pages/customer/project/index",
"style": {
    "navigationBarTitleText": "服务",
    //小程序
    "navigationStyle": "custom",
     //App、H5
    "app-plus": {
	"titleNView": false //禁用原生导航栏
        }
    }
},

2. 封装navbar组件

  1. 获取状态栏和导航栏的高度
// 获取手机系统信息
const info = uni.getSystemInfoSync()
// 设置状态栏高度(H5顶部无状态栏小程序有状态栏需要撑起高度)
this.statusBarHeight = info.statusBarHeight
// 除了h5 app mp-alipay的情况下执行
// #ifndef H5 || APP-PLUS || MP-ALIPAY
// 获取胶囊的位置
const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
// (胶囊底部高度 - 状态栏的高度) + (胶囊顶部高度 - 状态栏内的高度) = 导航栏的高度
this.navBarHeight = (menuButtonInfo.bottom - info.statusBarHeight) + (menuButtonInfo.top - info.statusBarHeight)

// #endif

2.通过props,slot在父组件自定义内容,this.$emit自定义事件

 props 让组件接收外部传过来的数据
 a. 传递数据:<Demo name="xxx" :age="18"/>
 注:如果需要传递表达式类型的值需要使用(:属性 = "xx")的写法
 b. 接收数据:
 第一种方式(只接收):props:['name']
 第二种方式(限制类型):props:{name:String}
 第三种方式(限制类型、限制必要性、指定默认值)
 props:{
     name:{
     type:String, //类型
     required:true, //必要性
     default:'老王' //默认值
     }
 }
 
 slot 在子组件指定位置插入html结构,也是一种组件间通信的方式
 
 自定义事件 
 a. 绑定自定义事件(父组件)@backPage="backSpace"
 b. 触发自定义事件(子组件)this.$emit('backPage')
<view class="nav-box">
    <view :style="{height:statusBarHeight+'px'}"></view>
    <view class="navbar cor333 f34" :style="{height:navBarHeight+'px'}">
            <view class="back" v-if="withBack" @tap="back">
                    <image src="/static/images/back-icon.png"  class="back-icon"></image>
            </view>
            <view v-else></view>
            <view class="title">{{ title }}</view>
            <slot name="right"></slot>
    </view>
</view>
<view :style="{height: statusBarHeight+'px'}" ></view>
props: {
    title: String,
    withBack: Boolean
},
methods: {
    back() {
        this.$emit('backPage')
    },
}

3.在全局引入、注册该组件

import navBar from './components/navbar/index.vue'
Vue.component('nav-bar', navBar)

4.在页面中使用组件

<nav-bar :title="navTitle" withBack @backPage="backSpace">
    <view slot="right" class="help-icon" @tap="goHelp">使用教程</view>
</nav-bar>
data() {
    return {
       navTitle:'任务列表',
    }
},
methods: {
   backSpace(){
        uni.redirectTo({
                url: '../index'
        })
    }
}


阅读量:896

点赞量:0

收藏量:0