一、環境配置與前置條件
-
?開發工具要求?
- HBuilderX 4.64+(鴻蒙插件已預裝)
- DevEco Studio 5.0.3.400+(真機調試必備)
- 鴻蒙離線SDK(通過HBuilderX導入,每個項目獨立配置)
-
?項目初始化
# 創建Vue3項目(鴻蒙僅支持Vue3)
npx degit dcloudio/uni-preset-vue#vite-ts my-project
在?manifest.json
?中聲明鴻蒙支持:
"harmonyos": {"appType": "ohos","packageName": "com.example.app","minPlatformVersion": 5 // 適配HarmonyOS 5
}
二、組件封裝核心原則
-
?API設計規范?
- 通過?
defineProps
?定義明確參數類型 - 使用?
@Prop
?聲明響應式屬性(ArkTS語法)
- 通過?
// components/DistributedButton.vue
<script setup>
defineProps({buttonText: { type: String, required: true },onClick: { type: Function, default: () => {} }
})
</script>
2.跨平臺兼容策略?
- 使用條件編譯隔離鴻蒙專屬邏輯:
<!-- #ifdef HARMONYOS -->
<harmony-card @touch="handleDistributedEvent">
<!-- #endif -->
? 3.性能優化
避免在組件內直接操作DOM(鴻蒙渲染引擎限制)
使用?Flex/Grid
?布局代替絕對定位
三、實戰組件封裝示例
案例1:分布式交互按鈕(跨設備控制)
<!-- components/HarmonyButton.vue -->
<template><button class="harmony-btn" @click="triggerAction"><!-- 鴻蒙專屬圖標 --><!-- #ifdef HARMONYOS --><span class="harmony-icon">📱</span><!-- #endif -->{{ buttonText }}</button>
</template><script setup>
import { ref } from 'vue'
const props = defineProps({ buttonText: String })const triggerAction = () => {// 鴻蒙分布式API調用// #ifdef HARMONYOSimport('@ohos.distributedHardware').then(module => {module.triggerDeviceAction('device_control')})// #endif
}
</script>
案例2:服務卡片組件
<!-- components/ServiceCard.vue -->
<template><harmony-card><template #header><text class="card-title">{{ title }}</text></template><slot name="content"></slot></harmony-card>
</template><style>
/* 適配鴻蒙的樣式 */
.harmony-card {border-radius: 8vp;background-color: #FFF;padding: 12vp;
}
</style>
四、模塊化開發最佳實踐
-
?工程結構規范
src/
├── components/ // 可復用組件
├── modules/ // 業務模塊(購物車、用戶等)
├── utils/ // 工具函數
└── hooks/ // 組合式API
? 2.狀態管理方案?
- 使用?
Pinia
?管理跨模塊狀態:
// modules/cartStore.ts
import { defineStore } from 'pinia'
export const useCartStore = defineStore('cart', {state: () => ({ items: [] }),actions: { addItem(item) { /* ... */ } }
})
五、調試與問題解決
-
?常見報錯處理?
?屬性未初始化?:為組件屬性設置默認值
@Prop title: string = "" // 必須初始化
??? ? ? ? ? API調用異常?:檢查?module.json5
?權限聲明?
"requestPermissions": ["ohos.distributedHardware.DISTRIBUTED_DATASYNC"
]
? ?性能監控工具
使用 DevEco Studio 的 ?ArkCompiler? 分析組件渲染性能