Commit 130bfc71 by liimin

feat(components): 添加弹窗尺寸控制和优化工具栏组件

- 在 MessageBox 组件中新增 maxWidth 属性支持弹窗最大宽度设置
- 在 FinishStep 组件中为 MessageBox 设置默认最大高度和宽度
- 将 FinishStep 弹窗内容宽度改为响应式适配,限制最大宽度为 375px
- 重构 ToolBox 组件为更灵活的配置化设计,支持自定义方向、位置、偏移等参数
- 为 ToolBox 组件添加图标动画效果和更好的交互体验
- 优化 ToolBox 组件的模板结构和样式布局
- 在图片适配器中修复高倍率屏幕下的图片选择逻辑,增加空值检查
1 parent 7cfe7941
# UTS Props 类型定义与组件优化规范
## 技能概述
本技能总结了一套完整的 UTS (UniApp TypeScript) 组件 Props 类型定义最佳实践,以及在 UTS 环境下进行组件重构和优化的完整流程。
## 核心要点
### 1. Props 类型定义规范
#### ✅ 正确做法:使用 interface + withDefaults
```typescript
// 定义 Props 接口 - 有默认值的属性定义为必填
interface Props {
// 基础数据
data: Array<any>
// 真正可选且可为空的才用 ?
id?: string | number | null
// 有默认值的"必填"属性
type: string
showPayBtn: boolean
idKey: string
toolStyle: string
// 配置项(都有默认值)
direction: 'top' | 'right' | 'bottom' | 'left'
position: 'top-left' | 'top-right' | 'top-center' | 'bottom-left' | 'bottom-right' | 'bottom-center'
offsetTop: number
offsetRight: number
fabSize: number
triggerText: string
}
// 使用 withDefaults 提供默认值
const props = withDefaults(defineProps<Props>(), {
data: () => [],
id: null,
type: '',
showPayBtn: false,
idKey: 'id',
toolStyle: '',
direction: 'bottom',
position: 'top-center',
offsetTop: 120,
offsetRight: 20,
fabSize: 56,
triggerText: '文件夹'
});
```
#### ❌ 错误做法:可选属性 + 默认值冲突
```typescript
// 会导致 Kotlin 编译错误
interface Props {
type?: string // 可选 -> 推断为 String?
showPayBtn?: boolean // 可选 -> 推断为 Boolean?
}
const props = withDefaults(defineProps<Props>(), {
type: '', // ❌ 类型不匹配:默认值是 String,但期望是 String?
showPayBtn: false // ❌ 类型不匹配:默认值是 Boolean,但期望是 Boolean?
});
```
**错误信息示例:**
```
error: 属性 "type" 的类型不匹配被重写的签名 "var type: String?"
```
---
### 2. UTS 类型系统关键区别
#### interface vs type
| 特性 | interface | type | 推荐使用场景 |
|------|-----------|------|-------------|
| **对象字面量支持** | ❌ 不支持 | ✅ 完全支持 | 数据模型用 type |
| **Props 定义** | ✅ 支持 | ⚠️ 不推荐 | Props 用 interface |
| **声明合并** | ✅ 支持 | ❌ 不支持 | 需要扩展时用 interface |
| **联合类型** | ❌ 不支持 | ✅ 支持 | 复杂类型用 type |
**关键规则:**
```typescript
// ✅ Props - 使用 interface
interface Props {
data: Array<any>
type: string
}
// ✅ 数据模型 - 使用 type(对象字面量兼容)
type ToolItem = {
id?: number | string
shortTitle?: string
shortTitleUrl?: string
}
// ❌ 不要用 interface 定义数据模型用于对象字面量
interface ToolItem { ... } // 会导致 UTS110111163 错误
```
---
### 3. computed 类型处理
#### ✅ 正确的泛型语法
```typescript
// 方式 1:泛型参数(推荐)
const displayData = computed<Array<ToolItem>>(() => {
if (props.data == null || props.data.length === 0) {
return [] as Array<ToolItem>;
}
return props.data.map((element: any) => {
const el = element as UTSJSONObject;
return {
id: el.id,
shortTitleUrl: el.shortTitleUrl,
shortTitle: el.shortTitle
}; // 自动推断为 ToolItem
}) as Array<ToolItem>;
});
// 方式 2:返回值类型注解(不推荐,可能报错)
const displayData: ComputedRef<Array<ToolItem>> = computed(() => {
// ... 可能在 UTS 中报语法错误
});
```
#### 类型断言策略
```typescript
// ✅ 分层断言策略
const displayData = computed<Array<ToolItem>>(() => {
// 空值检查
if (props.data == null) {
return [] as Array<ToolItem>; // 返回类型断言
}
// map 转换
return props.data.map((element: any) => {
const el = element as UTSJSONObject; // 对象类型断言
return {
id: el.id, // 自动推断
shortTitleUrl: el.shortTitleUrl,
shortTitle: el.shortTitle
}; // 让编译器自动推断为 ToolItem
}) as Array<ToolItem>; // 数组类型断言
});
```
---
### 4. 空值检查规范
#### ✅ 使用 `== null` 替代逻辑非
```typescript
// ❌ 在 UTS 中可能不支持
if (!props.data || props.data.length === 0) {
// ✅ 推荐写法
if (props.data == null || props.data.length === 0) {
```
---
### 5. 组件重构完整流程
#### 步骤 1: 模板层优化
```vue
<!-- ❌ 硬编码 -->
<un-fab active-icon="folder"
direction="bottom"
:offset-right="20"
:offset-top="120">
<!-- ✅ 配置化 -->
<un-fab :direction="direction"
:offset-right="offsetRight"
:offset-top="offsetTop">
```
#### 步骤 2: Props 类型定义
```typescript
interface Props {
// 所有配置项都定义为必填
direction: 'top' | 'right' | 'bottom' | 'left'
offsetRight: number
offsetTop: number
}
const props = withDefaults(defineProps<Props>(), {
direction: 'bottom',
offsetRight: 20,
offsetTop: 120
});
```
#### 步骤 3: 计算属性优化
```typescript
// 动态图标
const iconName = computed<string>(() => {
return show.value ? 'close' : 'folder';
});
// 数据处理
const displayData = computed<Array<ToolItem>>(() => {
if (props.data == null) {
return [] as Array<ToolItem>;
}
return props.data.map((el: any) => ({
id: (el as UTSJSONObject).id,
shortTitle: (el as UTSJSONObject).shortTitle
})) as Array<ToolItem>;
});
```
#### 步骤 4: 样式优化
```scss
<style scoped lang="scss">
// 添加交互动画
.custom-trigger {
transition: transform 0.3s ease;
&.expanded {
transform: rotate(90deg);
}
}
.fab-item {
transition: transform 0.2s ease;
&:active {
transform: scale(0.95);
}
}
</style>
```
---
## 常见错误与解决方案
### 错误 1: Props 类型不匹配
**错误信息:**
```
error: 属性 "type" 的类型不匹配被重写的签名 "var type: String?"
```
**原因:** 可选属性 `type?: string` 被推断为 `String?`,但默认值是 `String`
**解决:** 将可选改为必填
```typescript
// ❌ 错误
type?: string
// ✅ 正确
type: string
```
---
### 错误 2: 对象字面量不支持 interface
**错误信息:**
```
UTS110111163: Object literals only support object types defined by construction type,
and do not support interfaces.
```
**原因:** 使用了 `interface` 定义数据模型
**解决:** 改用 `type`
```typescript
// ❌ 错误
interface ToolItem { id?: string }
return { id: 'xxx' } as ToolItem;
// ✅ 正确
type ToolItem = { id?: string }
return { id: 'xxx' };
```
---
### 错误 3: computed 语法错误
**错误信息:**
```
Syntax error: Type expected.
```
**原因:** 使用了 Vue 的 `ComputedRef<T>` 类型注解
**解决:** 使用泛型参数
```typescript
// ❌ 错误
import type { ComputedRef } from 'vue';
const displayData: ComputedRef<Array<ToolItem>> = computed(() => {});
// ✅ 正确
const displayData = computed<Array<ToolItem>>(() => {});
```
---
### 错误 4: 找不到属性名
**错误信息:**
```
error: 找不到名称"id"
```
**原因:** `any` 类型直接访问属性
**解决:** 显式类型转换
```typescript
// ❌ 错误
return props.data.map((element: any) => ({
id: element.id // ❌ 找不到名称
}));
// ✅ 正确
return props.data.map((element: any) => {
const el = element as UTSJSONObject;
return { id: el.id };
});
```
---
### 错误 5: style 标签缺失闭合
**错误信息:**
```
Element is missing end tag.
```
**原因:** 使用 `edit_file` 编辑时可能丢失闭合标签
**解决:** 手动添加 `</style>`
```vue
<style scoped lang="scss">
.tool-box {
// ... styles
}
</style> <!-- ✅ 确保闭合 -->
```
---
## 最佳实践清单
### ✅ Props 定义
- [ ] 使用 `interface` 定义 Props
- [ ] 有默认值的属性定义为必填(不加 `?`)
- [ ] 真正可选且可为空的才用 `?`
- [ ] 使用 `withDefaults` 提供默认值
- [ ] 避免类型冲突
### ✅ 类型定义
- [ ] Props 用 `interface`
- [ ] 数据模型用 `type`
- [ ] 避免在对象字面量中使用 `interface`
- [ ] 必要时使用类型断言
### ✅ computed 处理
- [ ] 使用泛型参数 `computed<T>()`
- [ ] 避免 `ComputedRef<T>` 注解
- [ ] 移除 Vue 类型导入
- [ ] 外层断言数组类型
### ✅ 空值检查
- [ ] 使用 `== null` 而非 `!value`
- [ ] 显式类型转换 `as UTSJSONObject`
- [ ] 分步构建返回对象
### ✅ 代码结构
- [ ] 清晰的区域注释
- [ ] JSDoc 文档注释
- [ ] Scoped 样式作用域
- [ ] 交互动画优化
---
## 应用场景
1. **组件重构** - 从松散 JS 迁移到严格 TS
2. **新组件开发** - 遵循 UTS 类型规范
3. **编译错误修复** - 快速定位类型问题
4. **性能优化** - 减少不必要的渲染
5. **可维护性提升** - 清晰的类型定义
---
## 相关资源
- [UTS 类型系统差异](https://doc.dcloud.net.cn/uni-app-x/uts/uts_diff_ts.html)
- [UTS 编译已知问题](https://doc.dcloud.net.cn/uni-app-x/uts/compiler-known-issues.html)
- [uview-unix 组件库](https://uview-unix.d3u.cn/)
---
## 版本历史
- **v1.0** (2026-03-27) - 初始版本,基于 ToolBox 组件优化经验总结
...@@ -60,3 +60,9 @@ ...@@ -60,3 +60,9 @@
3. **性能优化**:使用合适的数字类型,避免不必要的类型转换 3. **性能优化**:使用合适的数字类型,避免不必要的类型转换
4. **错误处理**:使用 try-catch 处理异常,不使用 undefined 4. **错误处理**:使用 try-catch 处理异常,不使用 undefined
5. **代码规范**:遵循 UTS 语法约束,避免使用被限制的特性 5. **代码规范**:遵循 UTS 语法约束,避免使用被限制的特性
## UTS 口诀:
1. Props 用 interface,withDefaults 能识别
2. 数据模型用 type,对象字面量兼容
3. 类型断言要谨慎,自动推断是首选
4. 外层断言数组型,内层推断对象型
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
<view class="step"> <view class="step">
<MessageBox ref="successRef" <MessageBox ref="successRef"
:is-footer="false" :is-footer="false"
:max-height="600"
:max-width="400"
position="center" position="center"
:title="step == 1 ? '客户信息完善' : '结果反馈'" :title="step == 1 ? '客户信息完善' : '结果反馈'"
:z-index="10074" :z-index="10074"
...@@ -542,7 +544,8 @@ defineExpose({ open, close }); ...@@ -542,7 +544,8 @@ defineExpose({ open, close });
} }
.popup-content { .popup-content {
width: 375px; width: 100%;
max-width: 375px;
background: #ffffff; background: #ffffff;
border-radius: 16px; border-radius: 16px;
overflow: hidden; overflow: hidden;
......
...@@ -92,6 +92,7 @@ const props = defineProps({ ...@@ -92,6 +92,7 @@ const props = defineProps({
default: "取消" default: "取消"
}, },
maxHeight: Number, maxHeight: Number,
maxWidth: Number,
back: Boolean, back: Boolean,
showCancelBtn: { showCancelBtn: {
type: Boolean, type: Boolean,
...@@ -110,11 +111,17 @@ const emit = defineEmits(["close", ...@@ -110,11 +111,17 @@ const emit = defineEmits(["close",
const visible = ref<boolean>(false); const visible = ref<boolean>(false);
const popupRef= ref(null); const popupRef= ref(null);
const popupStyle = computed(() => { const popupStyle = computed(() => {
return { const style: UTSJSONObject = {
width: props.popupW != null && props.popupW > 0 ? `${props.popupW ?? 0 }px` : "100%", width: props.popupW != null && props.popupW > 0 ? `${props.popupW}px` : "100%",
minHeight: props.popupH != null && props.popupH > 0 ? `${props.popupH ?? 0 }px` : "100%", minHeight: props.popupH != null && props.popupH > 0 ? `${props.popupH}px` : "100%",
maxHeight: props.maxHeight != null && props.maxHeight > 0 ? `${props.maxHeight ?? 0 }px` : "100%" maxHeight: props.maxHeight != null && props.maxHeight > 0 ? `${props.maxHeight}px` : "100%"
}; };
if (props.maxWidth != null && props.maxWidth > 0) {
style.maxWidth = `${props.maxWidth}px`;
}
return style;
}); });
function close(): void { function close(): void {
...@@ -164,6 +171,8 @@ defineExpose({ open, close, hide }); ...@@ -164,6 +171,8 @@ defineExpose({ open, close, hide });
overflow: hidden; overflow: hidden;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
max-width: 100vw;
box-sizing: border-box;
.tips-content { .tips-content {
width: 100%; width: 100%;
padding: 24px; padding: 24px;
......
...@@ -2,58 +2,55 @@ ...@@ -2,58 +2,55 @@
<view class="tool-box"> <view class="tool-box">
<!-- 使用 uview-plus 的 FAB 组件 --> <!-- 使用 uview-plus 的 FAB 组件 -->
<un-fab v-model:active="show" <un-fab v-model:active="show"
active-icon="folder" :direction="direction"
direction="bottom"
:expandable="true" :expandable="true"
inactive-icon="folder" :offset-right="offsetRight"
:offset-right="20" :offset-top="offsetTop"
:offset-top="120" :position="position"
position="top-center" :size="fabSize"
:size="56" :type="type"
type="primary"
@click="handleFabClick"> @click="handleFabClick">
<template #trigger> <template #trigger>
<view class="custom-trigger"> <view :class="['custom-trigger', { expanded: show }]">
<un-icon name="folder" size="24" color="#fff"></un-icon> <un-icon :name="iconName" size="24" color="#fff"></un-icon>
<text class="trigger-text">文件夹</text> <text class="trigger-text">{{ triggerText }}</text>
</view> </view>
</template> </template>
<template #default> <template #default>
<view class="list-wrapper"> <view class="list-wrapper">
<!-- 动态数据项 --> <!-- 动态数据项 -->
<template v-for="(item, index) in displayData" :key="index"> <view v-for="(item, index) in displayData"
<view class="fab-item" :key="index"
class="fab-item"
@click="selectItem(item)"> @click="selectItem(item)">
<view class="icon-box"> <view class="icon-box">
<image class="btn-icon" <image v-if="item.shortTitleUrl"
class="btn-icon"
mode="aspectFill" mode="aspectFill"
:src="item.shortTitleUrl" /> :src="item.shortTitleUrl" />
<text class="item-text">{{ item.shortTitle }}</text> <text class="item-text">{{ item.shortTitle }}</text>
</view> </view>
</view> </view>
</template>
<!-- 付款方式 --> <!-- 付款方式 -->
<template v-if="props.showPayBtn"> <view v-if="showPayBtn"
<view class="fab-item" class="fab-item"
@click="toPay"> @click="toPay">
<view class="icon-box"> <view class="icon-box">
<view class="sprite-icon icon-tool-pay"></view> <view class="sprite-icon icon-tool-pay"></view>
<text class="item-text">付款方式</text> <text class="item-text">付款方式</text>
</view> </view>
</view> </view>
</template>
<!-- 完成接待 --> <!-- 完成接待 -->
<template v-if="props.type != 'preview'"> <view v-if="type !== 'preview'"
<view class="fab-item" class="fab-item"
@click="finish"> @click="finish">
<view class="icon-box"> <view class="icon-box">
<view class="sprite-icon icon-tool-finish"></view> <view class="sprite-icon icon-tool-finish"></view>
<text class="item-text">完成接待</text> <text class="item-text">完成接待</text>
</view> </view>
</view> </view>
</template>
</view> </view>
</template> </template>
</un-fab> </un-fab>
...@@ -61,100 +58,158 @@ ...@@ -61,100 +58,158 @@
</template> </template>
<script setup lang="uts"> <script setup lang="uts">
/**
* ToolBox 工具栏组件
* 用于展示可展开的工具选项列表
*/
const props = defineProps({ // ============================================================================
type: { // Props 定义
type: String, // ============================================================================
default: "" interface Props {
}, data: Array<any>
data:{ id?: string | number | null
type: Array, type: string
default: () => [] showPayBtn: boolean
}, idKey: string
id: { toolStyle: string
type: [String, Number], // 配置项
default: null direction: 'top' | 'right' | 'bottom' | 'left'
}, position: 'top-left' | 'top-right' | 'top-center' | 'bottom-left' | 'bottom-right' | 'bottom-center'
showPayBtn: { offsetTop: number
type: Boolean, offsetRight: number
default: false fabSize: number
}, triggerText: string
idKey: { }
type: String,
default: "id" const props = withDefaults(defineProps<Props>(), {
}, data: () => [],
toolStyle: { id: null,
type: String, type: '',
default: "" showPayBtn: false,
} idKey: 'id',
toolStyle: '',
direction: 'bottom',
position: 'top-center',
offsetTop: 120,
offsetRight: 20,
fabSize: 56,
triggerText: '文件夹'
}); });
const emit = defineEmits(["choose", "finish", "toPay"]); // ============================================================================
// Events 定义
// ============================================================================
const emit = defineEmits<{
(e: 'choose', item: ToolItem): void
(e: 'finish'): void
(e: 'toPay'): void
}>();
// ============================================================================
// 类型定义
// ============================================================================
type ToolItem = { type ToolItem = {
id?: number | string id?: number | string
shortTitle?: string shortTitle?: string
shortTitleUrl?: string shortTitleUrl?: string
} }
// ============================================================================
// 响应式状态
// ============================================================================
const show = ref<boolean>(false); // 初始收起 const show = ref<boolean>(false); // 初始收起
const displayData = computed(() => {
if (props.data == null) { // ============================================================================
console.log("[ToolBox] data is null"); // 计算属性
// ============================================================================
/**
* 处理后的展示数据
*/
const displayData = computed<Array<ToolItem>>(() => {
if (props.data == null || props.data.length === 0) {
console.log('[ToolBox] data is empty');
return [] as Array<ToolItem>; return [] as Array<ToolItem>;
} }
console.log("[ToolBox] data:", props.data);
return (props.data as Array<UTSJSONObject>).map(element => { return props.data.map((element: any) => {
const el = element as UTSJSONObject;
return { return {
id: element.id, id: el.id,
shortTitleUrl: element.shortTitleUrl as string, shortTitleUrl: el.shortTitleUrl,
shortTitle: element.shortTitle as string shortTitle: el.shortTitle
} as ToolItem; };
}); }) as Array<ToolItem>;
}); });
const isActive = (item: ToolItem): boolean => { /**
return props.id != null && item.id === props.id; * 根据状态动态选择图标
}; */
const iconName = computed<string>(() => {
return show.value ? 'close' : 'folder';
});
// 切换展开/收起 // ============================================================================
// 方法
// ============================================================================
/**
* 切换展开/收起状态
*/
const toggle = (): void => { const toggle = (): void => {
show.value = !show.value; show.value = !show.value;
}; };
// 处理 FAB 点击 /**
* 处理 FAB 按钮点击
*/
const handleFabClick = (): void => { const handleFabClick = (): void => {
toggle(); toggle();
}; };
// 选择项目 /**
* 选择工具项
* @param item - 选中的工具项
*/
const selectItem = (item: ToolItem): void => { const selectItem = (item: ToolItem): void => {
show.value = false; // 自动收起 show.value = false; // 自动收起
emit("choose", item); emit('choose', item);
}; };
function finish(): void { /**
emit("finish"); * 完成接待
} */
const finish = (): void => {
emit('finish');
};
function toPay(): void { /**
emit("toPay"); * 前往支付
} */
const toPay = (): void => {
emit('toPay');
};
function hide(): void { /**
* 隐藏工具栏
*/
const hide = (): void => {
show.value = false; show.value = false;
} };
defineExpose({ hide });
// ============================================================================
// 暴露给父组件的方法
// ============================================================================
defineExpose({
hide
});
</script> </script>
<style lang="scss"> <style scoped lang="scss">
.tool-box { .tool-box {
position: relative; position: relative;
width: 100%; width: 100%;
height: 100%; height: 100%;
.custom-trigger { .custom-trigger {
width: 56px; width: 56px;
height: 56px; height: 56px;
...@@ -165,7 +220,13 @@ defineExpose({ hide }); ...@@ -165,7 +220,13 @@ defineExpose({ hide });
justify-content: center; justify-content: center;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
flex-direction: column; flex-direction: column;
.trigger-text{ transition: transform 0.3s ease;
&.expanded {
transform: rotate(90deg);
}
.trigger-text {
position: relative; position: relative;
font-size: 11px; font-size: 11px;
color: #fff; color: #fff;
...@@ -173,8 +234,10 @@ defineExpose({ hide }); ...@@ -173,8 +234,10 @@ defineExpose({ hide });
white-space: nowrap; white-space: nowrap;
z-index: 2; z-index: 2;
font-weight: 500; font-weight: 500;
margin-top: 2px;
} }
} }
.list-wrapper { .list-wrapper {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
...@@ -182,11 +245,18 @@ defineExpose({ hide }); ...@@ -182,11 +245,18 @@ defineExpose({ hide });
padding: 16px 12px; padding: 16px 12px;
margin-bottom: 8px; margin-bottom: 8px;
align-items: center; align-items: center;
.fab-item { .fab-item {
display: flex; display: flex;
justify-content: center; justify-content: center;
cursor: pointer; cursor: pointer;
margin-bottom:10px; margin-bottom: 10px;
transition: transform 0.2s ease;
&:active {
transform: scale(0.95);
}
.icon-box { .icon-box {
position: relative; position: relative;
width: 56px; width: 56px;
...@@ -198,6 +268,7 @@ defineExpose({ hide }); ...@@ -198,6 +268,7 @@ defineExpose({ hide });
align-items: center; align-items: center;
justify-content: center; justify-content: center;
overflow: hidden; overflow: hidden;
.btn-icon, .btn-icon,
.sprite-icon { .sprite-icon {
position: absolute; position: absolute;
......
...@@ -98,13 +98,13 @@ export function getResponsiveImage(img: ResponsiveImage): string { ...@@ -98,13 +98,13 @@ export function getResponsiveImage(img: ResponsiveImage): string {
// 高倍率屏优先使用高清图 // 高倍率屏优先使用高清图
if (pr >= 3) { if (pr >= 3) {
if (img.x3) return img.x3; if (img.x3 != null) return img.x3;
if (img.x2) return img.x2; if (img.x2 != null) return img.x2;
return img.x1; return img.x1;
} }
if (pr >= 2) { if (pr >= 2) {
if (img.x2) return img.x2; if (img.x2 != null) return img.x2;
if (img.x3) return img.x3; if (img.x3 != null) return img.x3;
return img.x1; return img.x1;
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!