更新记录

1.0.0(2026-01-28) 下载此版本

  • 初始版本发布,包含基础 UI 组件库。
  • 完善 README.md 组件库文档,包含详细的组件用法与属性说明。

平台兼容性

uni-app(4.0)

Vue2 Vue3 Chrome Safari app-vue app-nvue Android iOS 鸿蒙
× - -
微信小程序 支付宝小程序 抖音小程序 百度小程序 快手小程序 京东小程序 鸿蒙元服务 QQ小程序 飞书小程序 小红书小程序 快应用-华为 快应用-联盟
- - - - - - - - - - -

NG-UI(ng-view)组件库使用文档

NG-UI 是一套轻量级的 uni-app UI 组件库(当前仓库的 uni_modules 插件:ng-view),包含常用基础组件 + 一套可选的全局工具库(路由、请求、存储、音频、hooks、工具函数等)。

本组件库的组件源码使用了 <script setup>,更推荐在 uni-app Vue3 项目中使用。


目录


1. 安装与引入

1.1 作为 uni_modules 插件使用

将本目录发布到 uni-app 插件市场后,用户在 HBuilderX 中“下载并导入”即可。

1.2 开启 easycom(推荐)

为了能够直接在页面中使用 <ng-button /> 这类标签,建议在项目根目录 pages.json 中配置 easycom 自动引入:

{
  "easycom": {
    "autoscan": true,
    "custom": {
      "^ng-(.*)$": "@/uni_modules/ng-view/components/ng-$1/ng-$1.vue"
    }
  }
}

配置完成后,即可在任意页面直接使用组件标签,无需手动 import


2. 推荐的全局初始化(可选)

NG-UI 提供了一个可选的“全局能力注入”,用于统一维护主题色、组件预设、图片路径拼接、request 默认配置等,并在运行时注入到:

  • uni.$ng(全局对象)
  • this.$ng(Options API)
  • app.config.globalProperties.$ng(Vue3 全局属性)
  • app.provide("$ng", ng)(Composition API 注入)

2.1 Vue3(uni-app)main.js 示例

import { createSSRApp } from "vue";
import App from "./App.vue";
import NgUI from "@/uni_modules/ng-view/index.js";

export function createApp() {
  const app = createSSRApp(App);

  app.use(NgUI, {
    color: {
      primary: "#2979ff",
      danger: "#fa3534",
    },
    button: {
      primary: {
        backgroundColor: "#2979ff",
        color: "#fff",
      },
    },
    text: {
      primary: {
        color: "#fff",
        fontSizs: "20rpx",
      },
    },
    image: {
      getServer: "https://static.example.com/",
      getStatic: "",
    },
    request: {
      baseURL: "https://api.example.com",
      token: {
        key: "token",
        headerName: "Authorization",
        prefix: "Bearer ",
      },
    },
  });

  return { app };
}

2.2 不装插件也能用(按需引入)

你也可以只使用组件(easycom)而不做全局安装;此时:

  • 组件内部若依赖 uni.$ng.config 的能力(例如 ng-image 通过 image.getServer/getStatic 拼接地址、ng-button 通过 button[preset] 获取预设样式),将使用空配置(不报错,但不会有预设效果)。

3. 全局配置说明

默认配置定义在:default.js

可传入 app.use(NgUI, config)config 会与默认配置做深度合并(deepMerge),最终存入 uni.$ng.config

3.1 config 结构

  • color: Record<string, string>
    主题色映射表,配合 getColor() 使用。示例:{ primary: "#2979ff" }
  • text: Record<string, object> 文本预设(ng-textpreset 会读取这里)
  • button: Record<string, object>
    按钮预设(ng-buttonpreset 会读取这里)
  • image: { getStatic: string | (path)=>string, getServer: string | (path)=>string }
    图片路径拼接策略(ng-image 使用)
  • request: {...}
    请求默认配置(libs/core/request.js 使用,详见 request

4. 通用样式 Props(allProps)

部分布局组件(ng-view/ng-flex/ng-grid)支持 ...allProps,这些属性用于快速组装通用布局样式。

实现位置:props.js

4.1 背景类(backgroundProps)

Prop 类型 默认值 说明
bg string - 直接设置 background(优先级高)
bgColor string - 背景色,支持主题色名称(走 getColor
bgImage string - 背景图 URL,将转换为 background-image: url(...)

4.2 外边距(marginProps)

Prop 类型 默认值 说明
margin string - 简写:直接写完整 CSS 值,例如 "10px 12px"
mt string | number - margin-top,number 默认单位为 rpx
mb string | number - margin-bottom
ml string | number - margin-left
mr string | number - margin-right

注意:当你使用 margin 简写时,组件不会自动补单位,请传入完整 CSS 值(如 "10px 0")。

4.3 内边距(paddingProps)

Prop 类型 默认值 说明
padding string - 简写:直接写完整 CSS 值,例如 "20rpx 32rpx"
pt string | number - padding-top,number 默认单位为 rpx
pb string | number - padding-bottom
pl string | number - padding-left
pr string | number - padding-right

注意:当你使用 padding 简写时,组件不会自动补单位,请传入完整 CSS 值(如 "16rpx 24rpx")。

4.4 定位(positionProps)

Prop 类型 默认值 说明
position string - 设置 position,不传则不输出定位相关样式
top string | number - top,number 默认单位为 rpx
bottom string | number - bottom
left string | number - left
right string | number - right

4.5 装饰(decorationProps)

Prop 类型 默认值 说明
border string - 直接设置 border
round string | number - border-radius,number 默认单位 rpx
shadow string - 直接设置 box-shadow

4.6 单位规则(非常重要)

  • addUnit(number) 默认会补 rpx,例如 addUnit(20) => "20rpx"
  • 如果你需要 px,请直接传字符串:"20px"
  • 组件中大量 props(宽高、圆角、间距等)都会走 addUnit,因此 数值默认视为 rpx

5. 组件文档

本插件包含以下组件(均在 uni_modules/ng-view/components):

  • ng-button 按钮
  • ng-divider 分割线
  • ng-flex Flex 布局
  • ng-footer 底部操作栏
  • ng-gap 间隔/占位
  • ng-grid Grid 布局
  • ng-icon 图标
  • ng-image 图片
  • ng-modal 模态框
  • ng-navbar 导航栏
  • ng-overlay 遮罩层
  • ng-picker 通用选择器
  • ng-picker-area 省市区选择器
  • ng-popup 弹出层容器
  • ng-radio 单选
  • ng-status-bar 状态栏占位
  • ng-sticky 吸顶
  • ng-text 文本
  • ng-transition 过渡动画
  • ng-view 通用容器
  • ng-ui(占位组件,当前无逻辑)

说明:大多数组件都没有 defineExpose(),因此没有“通过 ref 调用的公开方法”。组件交互主要通过 props + 事件实现。


5.1 ng-button 按钮

源码:ng-button.vue

基础用法

<template>
  <ng-button preset="primary" text="确定" @click="onSubmit" />
  <ng-button text="去详情" path="/pages/detail/detail?id=1" />
  <ng-button :loading="loading" :disabled="disabled">自定义插槽文字</ng-button>
</template>

Props

Prop 类型 默认值 说明
wh string | number "" 宽高快捷设置,格式见 getWH()(默认按空格分隔)
preset string "" 预设样式名:读取 config.button[preset] 作为样式对象合并到按钮样式
width string | number "" 宽度
height string | number "" 高度
colGap string | number 12 内容间距(加载图标与文字之间)
text string "" 默认文案(当未传 slot 时显示)
color string "" 文本/加载图标颜色(支持主题色名)
fontSize string | number 28 文本字号
bold boolean false 文本是否加粗
disabled boolean false 禁用
loading boolean false 加载态(显示转圈)
throttleTime string | number 0 点击节流时间(ms),>0 时走 throttle
customTextStyle object | string {} 自定义文本样式(对象或 style 字符串)
customStyle object | string {} 自定义按钮样式(对象或 style 字符串)
formType string "" 透传原生 button 的 form-type
openType string "" 透传原生 button 的 open-type(禁用/加载时会置空)
hoverStartTime string | number 20 点击态延迟(ms)
hoverStayTime string | number 150 点击态保留(ms)
sessionFrom string "" 小程序会话来源
sendMessageTitle string "" 小程序消息卡片标题
sendMessagePath string "" 小程序消息卡片跳转路径
sendMessageImg string "" 小程序消息卡片图片
showMessageCard boolean false 是否显示消息卡片
appParameter string "" 打开 APP 参数
round string | number 8 圆角
border string "" 直接设置 border
borderColor string "" 边框颜色(与 borderWidth/borderStyle 组合)
borderWidth string | number "1px" 边框宽度
borderStyle string "solid" 边框样式
path string "" 点击后调用 router.push(path)

Events

  • click(e):按钮点击(配置 path 时不会触发,仅执行跳转)
  • getphonenumber/detailgetuserinfo/detailerror/detailopensetting/detaillaunchapp/detailcontact/detailchooseavatar/detailaddgroupapp/detailchooseaddress/detailsubscribe/detaillogin/detailim/detailagreeprivacyauthorization/detail:原生事件转发(emit 的参数为 e.detail

Slots

  • 默认插槽:存在时替换默认的 <text>{{text}}</text>

5.2 ng-divider 分割线

源码:ng-divider.vue

用法

<template>
  <ng-divider text="我是分割线" />
  <ng-divider dashed />
  <ng-divider dot />
  <ng-divider text-position="left">插槽文字</ng-divider>
</template>

Props

Prop 类型 默认值 说明
mt string | number 0 上外边距
mb string | number 0 下外边距
dashed boolean false 虚线
hairline boolean true 细线
dot boolean false 使用点替代文字
textPosition string "center" 文字位置:left/center/right
text string | number "" 文案(当默认插槽为空时生效)
textSize string | number 28 文案大小
textColor string "#909399" 文案颜色
lineColor string "#dcdfe6" 线条颜色
width string | number "100%" 分割线宽度

Events

  • click:点击分割线触发(原生 tap)

Slots

  • 默认插槽:分割线中间内容(优先于 text

5.3 ng-flex Flex 布局

源码:ng-flex.vue

用法

<template>
  <ng-flex jc="space-between" ai="center" :cg="16">
    <ng-text text="左" />
    <ng-text text="右" />
  </ng-flex>
</template>

Props

除下表外,还支持通用样式 Props:见 allProps

Prop 类型 默认值 说明
width string | number - 宽度
height string | number - 高度
wh string | number - 宽高快捷设置
direction string - flex-direction
wrap string - flex-wrap
jc string - justify-content
ai string - align-items
gap string | number - gap
rg string | number - row-gap
cg string | number - column-gap
grow number | string - flex-grow
shrink number | string - flex-shrink
basis number | string - flex-basis
ac string - align-content
as string - align-self
customStyle object {} 额外样式对象
center boolean false 快捷:同时设置水平+垂直居中
xCenter boolean false 快捷:水平居中
yCenter boolean false 快捷:垂直居中
flex boolean false 快捷:设置为弹性容器(内部实现以组件为准)
path string "" 点击后跳转(不触发 click 事件)

Slots

  • 默认插槽

5.4 ng-grid Grid 布局

源码:ng-grid.vue

用法

<template>
  <ng-grid :col="3" :gap="16" @click="onGridClick">
    <ng-view v-for="n in 6" :key="n" bgColor="#f5f5f5" height="100rpx" />
  </ng-grid>
</template>

Props

除下表外,还支持通用样式 Props:见 allProps

Prop 类型 默认值 说明
width string | number - 宽度
height string | number - 高度
wh string | number - 宽高快捷
col string | number 1 列数
row string | number - 行数(可选)
areas string - grid-template-areas
ai string - align-items
ji string - justify-items
jc string - justify-content
ac string - align-content
gap string | number - gap
rg string | number - row-gap
cg string | number - column-gap
path string - 点击后跳转(配置后不触发 click 事件)
opacity number | string - 透明度
hidden boolean false 隐藏(display/visibility 由组件实现)
zIndex number | string - 层级
customStyle object {} 额外样式对象

Events

  • click(e):点击触发(配置 path 时不会触发,仅执行跳转)

Slots

  • 默认插槽

5.5 ng-view 通用容器

源码:ng-view.vue

用法

<template>
  <ng-view
    bgColor="#fff"
    padding="24rpx"
    round="16"
    shadow="0 6rpx 20rpx rgba(0,0,0,0.08)">
    <ng-text text="内容区" />
  </ng-view>
</template>

Props

支持通用样式 Props:见 allProps

Prop 类型 默认值 说明
width string | number - 宽度
height string | number - 高度
wh string | number - 宽高快捷
round string | number 0 圆角
opacity number | string - 透明度
hidden boolean false 隐藏
shadow string - 阴影
border string - 边框
zIndex number | string - 层级
grow number | string - flex-grow
shrink number | string - flex-shrink
basis number | string - flex-basis
as string - align-self
js string - justify-self(如组件实现支持)
area string - grid-area(如组件实现支持)
customStyle object | string {} 自定义样式
path string "" 点击后跳转(配置后不触发 click 事件)

Events

  • click(e):点击触发(配置 path 时不会触发,仅执行跳转)

Slots

  • 默认插槽

5.6 ng-text 文本

源码:ng-text.vue

用法

<template>
  <ng-text text="标题" preset="h1" bold />
  <ng-text text="可点击" path="/pages/detail/detail" />
</template>

Props

Prop 类型 默认值 说明
text string | number - 文本内容
size string | number - 字号(number 默认 rpx)
color string "#030303" 文本颜色(支持主题色名)
preset string "" 文本预设名:读取 config.text[preset](如你在项目中配置了)
bold boolean false 加粗
decoration string - text-decoration
lineHeight string | number - line-height
letterSpacing string | number - letter-spacing
selectable boolean false 是否可选(透传 text selectable)
userSelect boolean false 是否允许 user-select
space string - space(透传 text)
decode boolean false decode(透传 text)
shadow string - text-shadow
align string - text-align
lines string | number - 超出行数省略(实现以组件为准)
block boolean false 是否块级展示
customStyle object {} 自定义样式
path string - 点击跳转(配置后不触发 click 事件)

Events

  • click(e):点击触发(配置 path 时不会触发,仅执行跳转)

5.7 ng-image 图片

源码:ng-image.vue

用法

<template>
  <ng-image src="https://example.com/a.png" wh="200 200" round="16" />

  <ng-image
    server-src="/images/a.png"
    :preview="true"
    :preview-list="['https://example.com/a.png', 'https://example.com/b.png']"
    :preview-current="0"
    wh="200 200" />

  <ng-image src="https://example.com/a.png" show-mask>
    <template #mask>
      <ng-text text="遮罩内容" color="#fff" />
    </template>
  </ng-image>
</template>

Props

支持外边距 Props(margin/mt/mb/ml/mr

Prop 类型 默认值 说明
src string - 完整图片地址(优先级最高)
staticSrc string "" 静态资源路径,可通过 config.image.getStatic 拼接
serverSrc string "" 服务器图片路径,可通过 config.image.getServer 拼接(优先于 staticSrc)
mode string "scaleToFill" 同 uni-app image 的 mode(内置 validator)
width string | number - 宽度
height string | number - 高度
wh string | number - 宽高快捷(getWH 按空格拆分)
round string | number 0 圆角
rotate string | number 0 旋转角度(deg)
duration string | number 0 旋转过渡时长(ms)
circle boolean false 圆形(强制 50% 圆角)
lazyLoad boolean true 懒加载
fadeShow boolean true 淡入
webp boolean false webp
showMenuByLongpress boolean false 长按菜单
errorImage string - 加载失败后替代图
showMask boolean false 是否显示遮罩
maskColor string "rgba(0,0,0,0.3)" 遮罩色
preview boolean false 是否启用预览(会调用 uni.previewImage
previewList array [] 预览列表(优先使用)
previewCurrent number 0 当前预览索引
bgColor string - 背景色
customStyle object | string {} 自定义样式
path string "" 点击跳转(配置后不触发 click 事件,preview 优先)

Events

  • click(e):点击触发(当 preview=false 且未配置 path
  • load(e):image load
  • error(e):image error

Slots

  • mask:自定义遮罩内容(showMask=true 时显示)

5.8 ng-icon 图标

源码:ng-icon.vue

用法

<template>
  <ng-icon name="arrow-right" />
  <ng-icon name="close" :size="40" color="#fa3534" bold @click="onClose" />
</template>

Props

Prop 类型 默认值 说明
name string "arrow-right" 图标名称(映射表见 components/ng-icon/icons.js
size number | string 30 图标大小
bold boolean false 是否加粗
color string "#000" 颜色(支持主题色名)
customStyle object | string {} 自定义样式

Events

  • click(e)

5.9 ng-overlay 遮罩

源码:ng-overlay.vue

用法

<template>
  <ng-overlay :show="show" @click="show = false" />
</template>

Props

Prop 类型 默认值 说明
show boolean false 是否显示
zIndex string | number 10070 层级
duration string | number 300 动画时长
opacity string | number 0.5 透明度 0-1
bgColor string "" 背景色
customClass string "" 自定义类名
customStyle object | string {} 自定义样式

Events

  • click

Slots

  • 默认插槽:遮罩内容(会通过 transition 渲染)

5.10 ng-transition 过渡动画

源码:ng-transition.vue

用法

<template>
  <ng-transition
    :show="show"
    mode="fade-zoom"
    @afterEnter="onOpen"
    @afterLeave="onClose">
    <ng-view bgColor="#fff" padding="24rpx">内容</ng-view>
  </ng-transition>
</template>

Props

Prop 类型 默认值 说明
show boolean false 是否展示
mode string "fade" 动画模式(见下方列表)
duration string | number 300 时长(ms)
timingFunction string "ease-out" 过渡曲线
customClass string "" 自定义类名
customStyle object | string {} 自定义样式

mode 可选值

动画映射定义在:nvue.ani-map.js

  • fade
  • fade-up
  • fade-down
  • fade-left
  • fade-right
  • slide-up
  • slide-down
  • slide-left
  • slide-right
  • zoom
  • fade-zoom

Events

  • click(e)
  • beforeEnter / enter / afterEnter
  • beforeLeave / leave / afterLeave

5.11 ng-popup 弹出层

源码:ng-popup.vue

用法

<template>
  <ng-button text="打开" @click="show = true" />
  <ng-popup
    :show="show"
    mode="bottom"
    round="24"
    closeable
    @open="onOpen"
    @close="show = false">
    <ng-view padding="24rpx">弹窗内容</ng-view>
  </ng-popup>
</template>

Props

Prop 类型 默认值 说明
show boolean false 是否显示
overlay boolean true 是否显示遮罩
mode string "bottom" top/bottom/left/right/center
duration string | number 300 动画时长
closeable boolean false 是否显示关闭图标
overlayStyle object | string {} 自定义遮罩样式
closeOnClickOverlay boolean true 点击遮罩是否关闭(会 emit close)
zIndex string | number 10075 层级
safeAreaInsetBottom boolean true 底部安全区占位
safeAreaInsetTop boolean false 顶部安全区占位
closeIconPos string "top-right" top-left/top-right/bottom-left/bottom-right
round string | number 0 圆角
zoom boolean true mode=center 时是否缩放
bgColor string "#fff" 背景色
closeIcon string "close" 关闭图标
closeIconColor string "#333" 关闭图标颜色
closeIconSize string | number "30" 关闭图标大小
overlayOpacity number | string 0.5 遮罩透明度
customStyle object | string {} 自定义内容样式

Events

  • open:弹窗动画进入完成后触发
  • close:请求关闭(点击遮罩/关闭按钮会 emit;真正关闭由外部将 show=false 完成)
  • click:点击弹窗区域触发(center 模式下会触发 overlayClick 逻辑)

Slots

  • 默认插槽:弹窗内容

5.12 ng-modal 模态框

源码:ng-modal.vue

用法(同步关闭)

<template>
  <ng-modal
    :show="show"
    title="提示"
    content="确定删除吗?"
    :show-cancel-button="true"
    @confirm="onConfirm"
    @cancel="show = false"
    @close="show = false" />
</template>

用法(asyncClose)

asyncClose=true 时,点击“确认”会进入 loading 状态,但不会自动关闭,你需要在异步成功后将 show=false

<template>
  <ng-modal
    :show="show"
    title="提交中"
    content="请稍候..."
    :async-close="true"
    @confirm="submit"
    @close="show = false" />
</template>

Props

Prop 类型 默认值 说明
show boolean false 是否显示
title string "" 标题
content string "" 内容(默认插槽优先于 content)
confirmText string "确认" 确认按钮文本
cancelText string "取消" 取消按钮文本
showConfirmButton boolean true 显示确认按钮
showCancelButton boolean false 显示取消按钮
confirmColor string "#2979ff" 确认按钮颜色
cancelColor string "#606266" 取消按钮颜色
buttonReverse boolean false 反转按钮位置
zoom boolean true 中心弹出缩放
asyncClose boolean false 确认按钮异步关闭(内部只做 loading,不做关闭)
closeOnClickOverlay boolean false 点击遮罩是否允许关闭(closeHandler 会判断)
negativeTop string | number 0 向上偏移量
width string | number "600" 宽度
radius string | number 12 圆角
titleStyle object | string {} 标题样式
contentStyle object | string {} 内容样式
confirmTextStyle object | string {} 确认文案样式
cancelTextStyle object | string {} 取消文案样式
duration string | number 400 动画时长

Events

  • confirm:点击确认
  • cancel:点击取消
  • close:点击遮罩请求关闭(需 closeOnClickOverlay=true

Slots

  • 默认插槽:内容区(替代 content
  • title:标题区
  • footer:底部整块替换
  • confirmButton:仅一个确认按钮区域
  • cancel:取消按钮自定义
  • confirm:确认按钮自定义

5.13 ng-navbar 导航栏

源码:ng-navbar.vue

用法

<template>
  <ng-navbar title="首页" @leftClick="onBack" />
  <ng-navbar>
    <template #center>
      <ng-text text="自定义标题" />
    </template>
    <template #right>
      <ng-icon name="close" @click="onClose" />
    </template>
  </ng-navbar>
</template>

Props

Prop 类型 默认值 说明
height string | number "44px" 主栏高度(不含状态栏)
bgColor string "#fff" 背景色
title string "" 标题
titleColor string "#000" 标题色
titleSize string | number "34rpx" 标题字号
titleWeight string | number "bold" 标题字重
leftIconName string "arrow-left" 左侧图标
leftIconSize string | number "40" 左侧图标大小
leftIconColor string "#000" 左侧图标颜色
back boolean true 是否显示返回图标
fixed boolean true 是否 fixed 顶部
placeholder boolean true fixed 时是否占位
zIndex string | number 98 层级
autoBack boolean true 点击左侧是否自动 uni.navigateBack()
customStyle object | string {} 自定义样式

Events

  • leftClick:点击左侧区域触发

Slots

  • 默认插槽:整体自定义(覆盖默认 left/center/right 结构)
  • center:中间区域
  • right:右侧区域

5.14 ng-tabs 选项卡

源码:ng-tabs.vue

用法

<template>
  <ng-tabs :list="list" v-model="current" @change="onChange" />
</template>

<script setup>
const current = ref(0);
const list = ref([{ name: "推荐" }, { name: "热门" }, { name: "最新" }]);
const onChange = (index) => {
  console.log("当前选中:", index);
};
</script>

Props

Prop 类型 默认值 说明
modelValue / current number | string 0 当前选中的索引
list Array [] 标签列表,如 [{name: '标签1'}]
keyName string "name" 从 list 对象中提取标签名的键名
scrollable boolean true 是否开启滚动模式
lineColor string "#3c9cff" 滑块颜色
lineWidth string | number 30 滑块宽度
lineHeight string | number 6 滑块高度
lineBgSize string "cover" 滑块背景尺寸
duration number 200 动画时长(ms)
activeStyle object | string { color: '#3c9cff', fontWeight: 'bold' } 激活标签样式
inactiveStyle object | string { color: '#303133' } 未激活标签样式
itemStyle object | string { height: '44px' } 单个 tab 的容器样式
mask object {} 标签的遮罩配置
isMask boolean false 是否显示遮罩
customStyle object | string {} 自定义样式

Events

  • change:点击标签时触发,返回索引
  • click:点击标签时触发,返回标签对象
  • longPress:长按标签时触发,返回索引

5.15 ng-radio 单选

源码:ng-radio.vue

用法

<template>
  <ng-radio v-model="checked" :name="true" label="同意协议" />
</template>

Props

Prop 类型 默认值 说明
modelValue boolean | string | number false v-model 值
checked boolean | string | number null 选中值(组件内部判定逻辑以源码为准)
name boolean | string | number true 当前项的值
size number | string - 整体大小
label string - 文案
labelColor string "" 文案颜色
labelSize number | string 30 文案大小
iconColor string - 图标颜色
iconSize number | string 30 图标大小
disabled boolean false 禁用
shape string "circle" circle
activeColor string "#FFB05C" 选中颜色
inactiveColor string "#666" 未选中颜色
customStyle object | string {} 自定义样式

Events

  • update:modelValue(value)
  • change(value)

5.16 ng-price 价格显示

源码:ng-price.vue

用法

<template>
  <ng-price price="99.9" symbol="¥" color="#ff0000" :intSize="40" />
</template>

Props

Prop 类型 默认值 说明
price number | string 0 价格数值
symbol string "¥" 货币符号
symbolSize string | number 24 货币符号字体大小
intSize string | number 32 整数部分字体大小
decSize string | number 24 小数部分字体大小
bold boolean false 是否加粗
color string "#333" 颜色
customStyle object | string {} 自定义样式

Events

  • click:点击价格时触发

5.17 ng-status-bar 状态栏占位

源码:ng-status-bar.vue

Props

Prop 类型 默认值 说明
bgColor string "transparent" 背景色

5.18 ng-sticky 吸顶

源码:ng-sticky.vue

用法

<template>
  <ng-sticky :offset-top="0" bg-color="#fff">
    <ng-view padding="24rpx">吸顶内容</ng-view>
  </ng-sticky>
</template>

Props

Prop 类型 默认值 说明
offsetTop string | number 0 sticky top
zIndex string | number 99 层级
bgColor string "transparent" 背景色
disabled boolean false 禁用吸顶
customStyle object {} 自定义样式

Slots

  • 默认插槽

5.19 ng-footer 底部栏

源码:ng-footer.vue

用法

<template>
  <ng-footer>
    <ng-button preset="primary" text="提交" />
  </ng-footer>
</template>

Props

Prop 类型 默认值 说明
fixed boolean true 固定底部
placeholder boolean true fixed 时是否占位
height string | number 100 高度
padding string - 内边距(需要自带单位)
borderTop string - 顶部分割线 border
shadow string - 阴影
safeArea boolean true 底部安全区
zIndex string | number 98 层级
ai string "center" align-items
jc string "center" justify-content
cg string | number 0 column-gap
customStyle object {} 自定义样式

Slots

  • 默认插槽

5.20 ng-gap 间隔

源码:ng-gap.vue

Props

Prop 类型 默认值 说明
height string | number 20 高度
bgColor string "#f5f5f5" 背景色
mt string | number 0 上外边距
mb string | number 0 下外边距

5.21 ng-picker-area 省市区选择器

源码:ng-picker-area.vue

用法

<template>
  <ng-button text="选择地区" @click="show = true" />
  <ng-picker-area
    v-model:show="show"
    v-model="areaNames"
    title="选择地区"
    @confirm="onConfirm" />
</template>

<script setup>
import { ref } from "vue";
const show = ref(false);
const areaNames = ref([]); // 形如 ["广东省","深圳市","南山区"]
const onConfirm = (result) => {
  // result.value: 名称数组
  // result.code: 代码数组
  // result.province/city/district: 对象
};
</script>

Props

Prop 类型 默认值 说明
show boolean false 控制弹窗显示
title string "选择地区" 标题
modelValue array [] 默认值:名称数组(长度 3)
confirmColor string "#3c9cff" 确认颜色
cancelColor string "#909193" 取消颜色
confirmText string "确定" 确认文案
cancelText string "取消" 取消文案
closeOnClickOverlay boolean true 点击遮罩关闭(由内部 ng-popup 控制)
zIndex number | string 10075 层级(透传给 ng-popup)
activeItemClass string "" 选中项自定义类名
inactiveItemClass string "" 未选中项自定义类名
activeItemStyle object | string {} 选中项自定义样式
inactiveItemStyle object | string {} 未选中项自定义样式

Events

  • update:show(boolean):关闭/打开
  • update:modelValue(array):确认时更新名称数组
  • confirm(result):确认选择(包含 province/city/district/value/code)
  • cancel:关闭触发
  • change(payload):picker 滚动变化

5.21 ng-picker 通用选择器

源码:ng-picker.vue

用法

<template>
  <!-- 单列 -->
  <ng-picker v-model:show="show1" :columns="columns1" @confirm="onConfirm" />

  <!-- 多列联动 -->
  <ng-picker v-model:show="show2" :columns="columns2" @confirm="onConfirm" />
</template>

<script setup>
import { ref } from "vue";
const show1 = ref(false);
const columns1 = ref([["中国", "美国", "日本"]]);

const show2 = ref(false);
const columns2 = ref([
  {
    text: "中国",
    children: [{ text: "北京" }, { text: "上海" }],
  },
  {
    text: "美国",
    children: [{ text: "纽约" }, { text: "洛杉矶" }],
  },
]);
</script>

Props

Prop 类型 默认值 说明
show boolean false 控制弹窗显示
columns array [] 数据列表
title string "" 标题
modelValue array [] 默认选中项索引
keyName string "text" 选项对象中显示的键名
confirmColor string "" 确认按钮颜色
cancelColor string "" 取消按钮颜色
confirmText string "确定" 确认文案
cancelText string "取消" 取消文案
closeOnClickOverlay boolean true 点击遮罩关闭
zIndex number | string 10075 层级
activeItemClass string "" 选中项自定义类名
inactiveItemClass string "" 未选中项自定义类名
activeItemStyle object | string {} 选中项自定义样式
inactiveItemStyle object | string {} 未选中项自定义样式

Events

  • update:show(boolean):显示状态改变
  • confirm(result):点击确定,返回 { value: 选中项数组, index: 索引数组 }
  • cancel:点击取消
  • change(payload):选项改变

5.22 ng-upload 上传(选择文件 + 预览)

源码:ng-upload.vue

用法(受控 fileList)

ng-upload 采用“受控”模式:外部维护 fileList,组件仅通过事件回调通知你新增/删除/超限等动作。

<template>
  <ng-upload
    :file-list="fileList"
    :max-count="9"
    :max-size="2 * 1024 * 1024"
    upload-text="上传"
    @afterRead="onAfterRead"
    @delete="onDelete"
    @oversize="onOversize" />
</template>

<script setup>
import { ref } from "vue";
const fileList = ref([]);

const onAfterRead = ({ file }) => {
  const files = Array.isArray(file) ? file : [file];
  // files: 选择到的临时文件列表
  // 你可以在这里上传到服务器,然后把 url 写回 fileList
};

const onDelete = ({ index }) => {
  fileList.value.splice(index, 1);
};

const onOversize = () => {
  uni.showToast({ title: "文件过大", icon: "none" });
};
</script>

Props

Prop 类型 默认值 说明
accept string "image" image/video/其他(内部识别扩展名)
capture string | array ["album","camera"] 选择来源
compressed boolean true 图片是否压缩
camera string "back" 摄像头方向
maxDuration string | number 60 视频最大时长
uploadIcon string "image-empty" 上传按钮图标
uploadIconColor string "#D3D4D6" 上传按钮图标色
useBeforeRead boolean false 是否启用 beforeRead 回调模式(见 Events)
previewFullImage boolean true 点击图片是否全屏预览
maxCount string | number 52 最大数量
disabled boolean false 禁用
imageMode string "aspectFill" 预览图 mode
name string "" 字段名(会在事件 detail 中返回)
sizeType array ["original","compressed"] sizeType 透传
multiple boolean false 是否多选
deletable boolean true 是否允许删除
maxSize string | number Number.MAX_VALUE 最大文件大小(字节)
fileList array [] 文件列表(受控)
uploadText string "" 上传按钮文案
width string | number 80 预览块宽度
height string | number 80 预览块高度
customStyle object | string {} 自定义样式
previewImage boolean true 是否展示预览区

重要:组件内部还会读取 props.beforeRead(函数)作为同步/异步拦截,但该 prop 未在 props.js 中显式声明。你仍然可以按 Vue 的“透传 props”方式传入:

  • :beforeRead="(file, detail) => true | false | Promise"

Events

  • beforeRead({ file, name, index, callback }):当 useBeforeRead=true 时触发;你需要手动调用 callback(true/false) 决定是否继续
  • afterRead({ file, name, index }):选择文件后触发(未超限)
  • oversize({ file, name, index }):超出 maxSize 触发
  • delete({ file, name, index }):点击删除触发(你需要更新外部 fileList)
  • clickPreview(payload):点击预览触发
  • error(error):chooseFile 失败或其他错误

Slots

  • 默认插槽:自定义上传按钮区域(替换默认上传按钮)

6. 工具库(libs)API 文档

工具库的入口导出见:libs/index.js

你可以通过两种方式使用工具库:

  1. 全局安装后:
const ng = uni.$ng; // 或 this.$ng / inject("$ng")
ng.request.get("/user");
  1. 按需导入:
import {
  request,
  router,
  storage,
  systemInfo,
} from "@/uni_modules/ng-view/index.js";

6.1 createNGUI / install(插件入口)

入口文件:index.js

createNGUI(config?)

  • 作用:创建 $ng 实例并挂载到 uni.$ng
  • 返回:ngui 对象,包含全部导出的工具函数 + sys(systemInfo 结果)+ router/push/back 快捷方法 + config/version

install(app, config?)

  • 作用:Vue3 插件安装函数(内部调用 createNGUI)
  • 额外行为:
    • app.config.globalProperties.$ng = ngui
    • app.provide("$ng", ngui)

6.2 systemInfo()

源码:system.js

用法

import { systemInfo } from "@/uni_modules/ng-view/index.js";
const info = systemInfo();

返回字段(常用)

  • windowWidth/windowHeight
  • screenWidth/screenHeight
  • statusBarHeight
  • safeArea/safeAreaInsets
  • dpr
  • scaleFactor
  • 微信小程序额外:menuButtonHeight/menuButtonWidth/menuButtonTop/menuButtonRight/menuButtonBottom/menuButtonLeft

6.3 storage(带过期时间的存储)

源码:storage.js

默认前缀:NG_(仅影响 storage 工具自身,不影响 uni.setStorageSync 的其他 key)

API

  • storage.set(key, value, expireSeconds?) => boolean
    设置同步存储;expireSeconds 为秒,传入则会记录过期时间
  • storage.get(key, defaultValue?) => any
    获取同步存储;过期会自动清理并返回 defaultValue
  • storage.setAsync(key, value, expireSeconds?) => Promise<boolean>
  • storage.getAsync(key, defaultValue?) => Promise<any>
  • storage.remove(key) => boolean
  • storage.has(key) => boolean
  • storage.setMultiple({k:v,...})
  • storage.getMultiple(keys: string[]) => Record<string, any>
  • storage.clear() => boolean
    仅清除带 NG_ 前缀的 key
  • storage.getInfo() => { keys, size, limit }

6.4 router(轻量路由封装)

源码:router.js

特性:

  • 支持 push/replace/reLaunch/back
  • 支持 query 序列化(数组/对象会做特殊处理)
  • 支持 params(通过 storage 临时存储,跳转后调用 router.getParams() 取出并自动清理)
  • 支持导航守卫:beforeEach/afterEach/onError
  • 自动识别 tabBar:如果目标 path 是 tabBar 页面,会自动切换为 switchTab

API

  • router.push(path, options?) => Promise
    • options.modenavigateTo(默认)/redirectTo/reLaunch/switchTab/preloadPage
    • options.query:对象,会拼进 url
    • options.params:对象,不拼接到 url,通过 storage 透传
    • 其余字段(animationType 等)透传到 uni 跳转方法
  • router.replace(path, options?) => Promise(等价于 mode=redirectTo)
  • router.reLaunch(path, options?) => Promise
  • router.back(delta=1):返回;当栈深不足时回到首页 tabBar 或 pages[0]
  • router.getParams() => any:获取并清理通过 params 传递的数据
  • router.isTab(path) => boolean:判断是否 tabBar
  • router.beforeEach((to, next, redirect) => void | Promise):注册前置守卫,返回取消函数
  • router.afterEach((to)=>void):注册后置回调,返回取消函数
  • router.onError((error, to)=>void):注册错误回调,返回取消函数

push 示例(params 传对象)

router.push("/pages/detail/detail", {
  query: { id: 1 },
  params: { foo: "bar", deep: { a: 1 } },
});

// 在目标页 onLoad/onShow 中:
const params = router.getParams();

6.5 audioManager(全局音频控制器)

源码:audioController.js

事件名称

事件名 说明
onStart 开始播放
onItemEnded 单首播放结束
onListEnded 列表播放结束
onError 播放错误
onPause 暂停
onStop 停止
onReplaced 列表被替换
onTimeUpdate 播放进度更新
onWaiting 缓冲中
onCanplay 可以播放

API

  • audioManager.set(list, options?) - 设置播放列表
    • list:音频数组,每项至少包含 { src }
    • options.index:开始播放索引(默认 0)
    • options.playMode:播放模式(order/loop/random/single
    • options.debug:是否输出调试日志
    • options.itemEndedAt:触发结束回调的时间点数组(毫秒)
    • options.waitMs:列表级默认播放后等待时间(毫秒)
    • 顶层回调:如 onStart(){}, onItemEnded(){}
  • audioManager.play(index?, isManualAction?) - 播放指定索引
  • audioManager.toggle() - 切换播放/暂停
  • audioManager.pause() - 暂停
  • audioManager.stop() - 停止并清空状态
  • audioManager.seek(time) - 跳转到指定时间(秒)
  • audioManager.next() - 下一首
  • audioManager.prev() - 上一首
  • audioManager.setMode(mode) - 设置播放模式(order/loop/random/single
  • audioManager.setLoop(times) - 设置循环次数
  • audioManager.setPlaybackRate(rate) - 设置播放倍速(0.5-3.0)
  • audioManager.on(eventName, callback) - 订阅事件
  • audioManager.off(eventName, callback?) - 取消订阅
  • audioManager.getState() - 获取当前状态

6.6 request / createRequest

源码:request.js

导出形式:

  • request:默认实例(export default createRequest()
  • createRequest(instanceConfig):创建独立实例(独立拦截器、独立 baseURL 等)

全局配置来源

request 会合并以下配置(后者覆盖前者):

  1. 内置默认配置(DEFAULT_REQUEST_CONFIG)
  2. uni.$ng.config.request(如果你安装了插件并设置了 config)
  3. 实例级配置(createRequest(instanceConfig) 传入)
  4. 单次请求 options(request({ ... }) 传入)

request(options) 扩展字段

uni.request 官方参数基础上,额外支持:

  • baseURL:覆盖本次请求的 baseURL
  • needToken: boolean:是否自动注入 token(默认 true)
  • token: { enable, storage, key, headerName, prefix }:覆盖 token 策略
    • storage: "uni" | "ng":读取 token 的方式;ng 会用 storage.get()
  • returnType: "data" | "response":默认返回 res.data;传 "response" 则返回完整 response
  • validateStatus(statusCode) => boolean:自定义状态码成功判定

get/post/put/delete 快捷方法

  • request.get(url, data?, options?)
  • request.post(url, data?, options?)
  • request.put(url, data?, options?)
  • request.delete(url, data?, options?)

拦截器

request 同时支持两种拦截器:

  1. 配置数组形式(全局/实例配置中):
  • requestInterceptors: Function[]:入参为 requestOptions,返回可选的 requestOptions(支持 Promise)
  • responseInterceptors: Function[]:入参为 response,返回可选的 response(支持 Promise)
  1. 类 axios 形式(每个实例自带):
  • request.interceptors.request.use(onFulfilled, onRejected?) => id
  • request.interceptors.request.eject(id)
  • request.interceptors.request.clear()
  • request.interceptors.response.use(...)

abort(取消请求)

request.request() 返回的是 Promise,并附带:

  • promise.task:可拿到 RequestTask
  • promise.abort():内部调用 RequestTask.abort()

示例:

const p = request.get("/list");
// 取消
p.abort();

6.7 hooks

useCountDown(options?)

源码:useCountDown.js

  • 入参:{ onFinish?, interval=1000 }
  • 返回:
    • timeData:computed,包含 day/hour/minute/second/milliseconds/remain
    • remain:ref,剩余毫秒
    • start(ms):启动
    • stop():停止
    • reset(ms):重置

useAppUpdate(options)

源码:useAppUpdate.js

  • 入参:
    • api(params) => Promise<any>:请求版本信息的 API(必传,仅 APP-PLUS 下生效)
    • shouldUpdate(res) => boolean:判断是否需要更新(必传)
    • downloadUrlField: string:下载地址字段名(必传)
  • 返回状态:
    • versionData/hasUpdate/updating/downloadProgress/updateStatus/errorMessage/updateType
  • 返回方法:
    • checkUpdate({ currentVersion? }) => Promise<boolean>
    • handleUpdate() => Promise<boolean>
    • cancelUpdate()
    • resetUpdate()
    • 工具方法:normalizeDownloadUrl/isWgtUrl/isApkUrl/isAppStoreUrl/isIOS

useWechatLogin(options)

源码:useWechatLogin.js

  • 入参(关键):
    • miniProgramLoginApi:小程序登录 API(必传)
    • appLoginApi:APP/H5 微信登录 API(必传)
    • appleLoginApi:苹果登录 API(可选)
    • storageKeys: { tokenKey: string }(必传)
    • onLoginSuccess(res)(必传)
    • onLoginError(err)(可选)
  • 返回:
    • 状态:loading/error/isIOS
    • 小程序:getMiniProgramCode()handlePhoneAuth(authResult, agreedToTerms?)
    • APP/H5:handleAppLogin(agreedToTerms?)detectIOS()
    • iOS:handleAppleLogin(agreedToTerms?)
    • 工具:checkAgreement/checkPhoneAuthResult/showError

6.8 utils(工具函数)

libs/index.js 已全量导出所有工具函数,源码见:utils/index.js

单位与布局

  • px2rpx(px):px 转 rpx
  • rpx2px(rpx):rpx 转 px
  • addUnit(value, unit="rpx"):给数字补单位
  • getWH(wh, width, height) => { w, h }:解析宽高快捷值

颜色与配置

  • toHex(color):颜色转十六进制
  • convertColor(color):颜色格式转换
  • getColor(val):主题色映射
  • getComponentConfig(componentName, presetName):读取组件预设

样式

  • addStyle(customStyle, target="object"):样式格式转换
  • trim(str, pos="both"):去空格

校验

  • isEmpty(value):判断空
  • isObject(val):是否对象
  • isPhone(str):是否手机号
  • isEmail(str):是否邮箱
  • isIdCard(str):是否身份证
  • isNumber(value):是否数值
  • isPureNumber(str):是否纯数字

数据

  • deepMerge(target, ...sources):深度合并
  • deepClone(obj):深克隆
  • removeEmpty(obj, isDeep=false):过滤空值

辅助

  • padZero(num, length=2):补零
  • guid(len=32):生成 GUID
  • toast(title, options):显示提示
  • sleep(ms=30):延迟

DOM

  • getRect(context, selector, all=false):获取节点信息

函数式

  • throttle(fn, wait=500, immediate=true):节流
  • debounce(fn, wait=500, immediate=false):防抖

文件

  • base64ToTempPath(base64):base64 转临时路径

日历

  • calendar:农历/公历转换工具

设备与时间

  • getDevice():获取设备信息
  • timeFormat(date, fmt?):时间格式化
  • timeFrom(date, option?):相对时间

6.9 样式 Props 工具函数(props.js)

源码:props.js

  • backgroundStyle(props) => object
  • marginStyle(props) => object
  • paddingStyle(props) => object
  • positionStyle(props) => object
  • getAllStyles(props) => object:汇总以上样式
  • allProps:上述所有 props 的聚合对象(供组件 ...allProps 使用)

6.10 utils 全量导出

libs/index.js 已全量导出所有工具函数,可直接使用:

import { rpx2px, timeFormat, calendar, isPhone } from "@/uni_modules/ng-view";

完整列表见:utils/index.js

隐私、权限声明

1. 本插件需要申请的系统权限列表:

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

许可协议

MIT协议