NavHeader.vue 2.2 KB
<!--
 * @Date: 2026-01-29 21:09:28
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2026-02-02 18:25:30
 * @FilePath: /manulife-weapp/src/components/NavHeader.vue
 * @Description: 通用导航头组件,用于页面顶部固定导航栏,展示页面标题。
 * @Usage:
 * <NavHeader title="首页" />
 * <NavHeader title="详情" :show-back="true" />
-->
<template>
  <!-- Placeholder to prevent content from being hidden behind fixed header -->
  <div class="w-full h-[250rpx]"></div>
  <!-- Fixed Header -->
  <div class="fixed top-0 left-0 z-50 w-full h-[250rpx] bg-gradient-to-b from-[#1E3A8A] to-[#2563EB] pt-[100rpx]">
    <div class="relative w-full h-full flex items-center justify-center px-[32rpx]">
      <div v-if="canGoBack" class="absolute left-[32rpx] flex items-center justify-center w-[60rpx] h-[60rpx]" @tap="goBack">
        <IconFont name="left" size="18" color="#fff" />
      </div>
      <span class="text-white text-[35rpx] font-normal">{{ title }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import IconFont from '@/components/icons/IconFont.vue'

/**
 * Props definition
 * @property {String} title - Page title
 * @property {Boolean} [showBack] - Whether to show back button. If undefined, auto-detects based on page stack.
 */
const props = defineProps({
  title: {
    type: String,
    required: true
  },
  showBack: {
    type: Boolean,
    default: undefined
  }
})

const canGoBack = ref(false)

/**
 * Initialize back button state
 */
onMounted(() => {
  if (props.showBack !== undefined) {
    canGoBack.value = props.showBack
  } else {
    const pages = Taro.getCurrentPages()
    canGoBack.value = pages.length > 1
  }
})

/**
 * Handle back navigation
 * @description 智能处理返回逻辑,避免导航栈为空时报错
 */
const goBack = () => {
  const pages = Taro.getCurrentPages()

  if (pages.length > 1) {
    // 如果导航栈有多个页面,正常返回
    Taro.navigateBack()
  } else {
    // 如果导航栈只有1页,跳转到首页(避免报错)
    console.log('导航栈只有1页,跳转到首页')
    Taro.reLaunch({
      url: '/pages/index/index'
    })
  }
}
</script>