uniapp 开发微信小程序 头部适配

在 UniApp 中,在微信小程序开发中,头部适配可以通过修改 pages.json 中的 navigationStyle 配置项来实现,具体操作步骤如下:

  1. 进入 pages.json 文件

在 UniApp 项目的根目录中找到 pages.json 文件,打开该文件。

  1. 修改 navigationStyle 配置项

pages.json 文件中,可以为每一个页面单独设置导航栏样式,具体的配置项是 navigationStyle。该配置项可以取值为 defaultcustomnone,其中:

  • default 表示使用小程序默认导航栏(即右侧有一个返回图标的导航栏)。
  • custom 表示隐藏小程序默认导航栏,自定义头部,可以通过 CSS 样式来设置头部的样式。
  • none 表示不显示导航栏,页面将充满整个屏幕。

例如,如果需要自定义头部样式,可以在 pages.json 文件中为某个页面设置 navigationStyle: "custom" 配置项,示例代码如下:

{
    
    
  "pages": [
    {
    
    
      "path": "pages/index/index",
      "style": {
    
    
        "navigationBarTitleText": "首页",
        "navigationBarBackgroundColor": "#ffffff"
      },
      "navigationStyle": "custom"
    }
  ]
}
  1. index.vue 中实现头部自定义

index.vue 文件中,可以通过添加自定义头部组件来实现头部的自定义。具体操作步骤如下:

  1. index.vue 文件中,添加头部组件代码,示例代码如下:
<!-- 头部组件 -->
<template>
  <view class="custom-header">
    <view class="custom-header-back" @click="onBackClick">
      <image src="/static/images/back.png" class="custom-header-back-image" />
    </view>
    <view class="custom-header-title">{
   
   { title }}</view>
  </view>
</template>

<script>
  export default {
      
      
    props: {
      
      
      title: {
      
      
        type: String,
        default: ''
      }
    },
    methods: {
      
      
      onBackClick() {
      
      
        uni.navigateBack()
      }
    }
  }
</script>

<style scoped>
  /* 头部样式 */
  .custom-header {
      
      
    display: flex;
    height: 44px;
    background-color: #ffffff;
    border-bottom: 1px solid #eaeaea;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 99;
  }

  .custom-header-back {
      
      
    width: 44px;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .custom-header-back-image {
      
      
    width: 18px;
    height: 18px;
  }

  .custom-header-title {
      
      
    flex: 1;
    text-align: center;
    font-size: 17px;
    font-weight: bold;
    color: #333333;
  }
</style>
  1. index.vue 文件中使用头部组件,并传入参数 title,示例代码如下:
<!-- 使用头部组件 -->
<template>
  <view>
    <!-- 头部组件,通过 v-bind 动态绑定 title 参数 -->
    <custom-header :title="title"></custom-header>

    <!-- 页面内容 -->
    <view class="content">
      <text>{
   
   { message }}</text>
    </view>
  </view>
</template>

<script>
  import customHeader from '../../components/custom-header.vue'

  export default {
      
      
    components: {
      
      
      customHeader
    },
    data() {
      
      
      return {
      
      
        title: '首页', // 头部标题
        message: 'Hello, World!' // 页面内容
      }
    }
  }
</script>

<style scoped>
  /* 页面内容样式 */
  .content {
      
      
    padding-top: 44px; /* 头部高度 */
    background-color: #ffffff;
    height: 100%;
  }
</style>

index.vue 文件中,通过添加自定义头部组件和设置 padding-top 来实现头部自定义的适配。其中,padding-top: 44px 表示设置页面内容的顶部距离为头部的高度,确保内容不会被头部遮挡。

猜你喜欢

转载自blog.csdn.net/qq_27487739/article/details/131138114