uts-migration-checklist.md
2.84 KB
UTS 迁移清单(一次性避免 49 次修复)
迁移 Vue/Vuex 到 uni-app x 时,在动手改代码前按此清单逐项处理,可避免反复编译修复。
一、Store 访问
| 禁止 | 推荐 |
|---|---|
store.state.boutique (弱类型) |
直接导入 state: import { state } from '@/store/index.uts'
|
store.state.user.xxx |
state.user.xxx (强类型访问) |
直接 this.$store.state
|
Options API 中使用 mapState
|
更新: 现在 Store 使用 Class 定义 RootState,直接导入 state 对象即可获得完整的类型推断和代码提示。不再建议将 state 强转为 UTSJSONObject。
二、Ref 初始化
| 禁止 | 推荐 |
|---|---|
ref(null as any) |
`ref<any |
ref<Comp>(null) 组件 ref |
`ref<any |
原因:null as any 在 Kotlin 编译后可能 NPE。
三、模板 v-for 中的 item
| 禁止 | 推荐 |
|---|---|
{{ item['bannerImg'] }} |
{{ getPkg(item, 'bannerImg') }} |
:src="item.bannerImg"(item 为 any) |
:src="getPkg(item, 'bannerImg')" |
// 在 script 中定义
function getPkg(item: any, key: string): any {
if (item == null) return ''
const obj = item as UTSJSONObject
const v = obj[key]
return v != null ? v : ''
}
原因:UTS 可能把 item['key'] 解析成 String.get。
四、数字 key 的对象映射
| 禁止 | 推荐 |
|---|---|
Record<number, X> + { 1: {...}, 0: {...} }
|
用函数映射 |
const map = { 1: a, 0: b } as Record<number, X> |
`function getXxx(id: number): X |
function getSceneTypeItem(sceneId: number): SceneTypeItem | null {
if (sceneId == 1) return { title: '轻改', describe: '...', icon: '轻' }
if (sceneId == 0) return { title: '会员权益', describe: '...', icon: '权' }
return null
}
原因:数字 key 字面量易触发 Conflicting declarations / UTS110111101。
五、数字格式化
| 禁止 | 推荐 |
|---|---|
Number(x).toLocaleString() |
parseFloat((x as any).toString()).toString() |
x.toLocaleString() |
同上或自定义 formatNumber |
原因:UTS 的 Number 无 toLocaleString。
六、Storage / JSON 解析
| 禁止 | 推荐 |
|---|---|
直接 JSON.parse(raw)
|
用 parseStorageJson(key)
|
JSON.parse("") |
判空 + try-catch |
// 参考 api/system-api.uts 中的 parseStorageJson
function parseStorageJson(key: string): UTSJSONObject | null {
const raw = storage.get(key)
if (raw == null) return null
if (typeof raw == 'string') {
const s = (raw as string).trim()
if (s == '' || s.length == 0) return null
try {
return JSON.parse(s) as UTSJSONObject
} catch (_) {
return null
}
}
return raw as UTSJSONObject
}
原因:JSON.parse 空字符串会崩溃。