小程序学习(六):项目实战之 Navigation

124 阅读1分钟

一、分析组件

今天继续分析我们的原型设计 看看一共有多少种Header

1. 返回 & 标题

1692503962031.png

2. 左右两边Icon & 标题

1692503990620.png

1692504087932.png

1692504103204.png

最后可以分为两类 Header 右边有无操作的,这我们就可以做成一个通用组件

二、开发通用组件

1. 新建组件文件

1692504481951.png

2. 布局

使用了unocss 大大减少了 css代码量

<template>
  <view class="flex flex-justify-between flex-items-center p-30">
    <view class="left-container">
      <uni-icons type="arrow-left" size="24"></uni-icons>
    </view>

    <view class="center-container text-30">首页</view>

    <view class="right-container">
        <view class="right-wrapper flex flex-items-center">
              <uni-icons type="heart-filled" size="24"></uni-icons>

              <uni-icons class="ml-40" type="redo-filled" size="24"></uni-icons>
        </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.center-container {
  position: absolute;
  right: 50%;
  transform: translateX(50%);
}
</style>

1692505941106.png

3. 添加插槽与参数变成通用可控组件

  1. 添加了插槽 left 与 right
    <template>
      <view class="flex flex-justify-between flex-items-center p-30">
        <view class="left-container">
          <slot name="left">
            <uni-icons type="arrow-left" size="24" @click="onBack"></uni-icons>
          </slot>
        </view>
    
        <view class="center-container text-30">{{ title }}</view>
    
        <view class="right-container">
          <view class="right-wrapper flex flex-items-center">
            <slot name="right"></slot>
            <uni-icons v-if="share" class="ml-40" type="redo-filled" size="24"></uni-icons>
          </view>
        </view>
      </view>
    </template>
    
  2. 添加Props
  • title 用于header显示的文案
  • share 为是否可以分享当前页
  • onBack 为返回操作的方法,因为在不同页面有时需要返回的地方不同,这里做为可配置的
defineProps({
  title: {
    type: String
  },
  share: {
    type: Boolean,
    value: false
  },
  onBack: {
    type: Function,
    default() {
      router.back()
    }
  }
});

三、实际使用

  1. 在设计中遇到的四种显示方案我们都已经可以成功实现

image.png

<Header title="首页" share/>

<Header title="您的图表"/>

<Header title="家">
  <template #left>
    <uni-icons type="bars" size="30"></uni-icons>
  </template>
  <template #right>
    <uni-icons type="cart" size="30"></uni-icons>
  </template>
</Header>

<Header title="家" share>
  <template #left>
    <uni-icons type="bars" size="24"></uni-icons>
  </template>
  <template #right>
    <view class="bg-white p-15 center b-rd-20">
      <uni-icons type="heart" size="24" color="red"></uni-icons>
    </view>
  </template>
</Header>
  1. 还可以再把安全距离加上
const {safeAreaInsets} = uni.getSystemInfoSync();
<view :style="`height: ${safeAreaInsets?.top}rpx`"></view>