【HarmonyOS】鸿蒙应用开发中常用的三方库介绍和使用示例
截止到2025年,目前参考官方文档:访问 HarmonyOS三方库中心 。梳理了以下热门下载量和常用的三方库。
上述库的组合,可快速实现网络请求、UI搭建、状态管理等核心功能,显著提升开发效率。
版本号以三方库网站上的版本号最新为准。
一、网络与数据交互
1. ohos-axios(网络请求)
ohos-axios:适配 HarmonyOS 的 Axios 版本,支持 HTTP/HTTPS 请求、拦截器、请求取消等,语法与 Web 端 Axios 一致,降低学习成本。
json
"dependencies": {
"@ohos/axios": "1.3.2"
}
typescript
import axios from '@ohos/axios';
// 基础配置
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 5000;
// 发送GET请求
async function fetchData() {
try {
const response = await axios.get('/user', {
params: { id: 123 }
});
console.log('请求成功:', response.data);
} catch (error) {
console.error('请求失败:', error);
}
}
// 拦截器示例
axios.interceptors.request.use(
(config) => {
// 添加Token
config.headers.Authorization = 'Bearer token';
return config;
},
(error) => Promise.reject(error)
);
2. ohos-websocket(实时通讯)
ohos-websocket:封装 WebSocket 客户端,支持长连接、消息监听、断线重连,适用于实时聊天、数据推送场景。
json
"dependencies": {
"@ohos/websocket": "2.1.0"
}
typescript
import WebSocket from '@ohos/websocket';
// 初始化连接
const ws = new WebSocket('wss://echo.websocket.events');
// 连接成功
ws.onopen = () => {
console.log('WebSocket连接已打开');
ws.send('Hello WebSocket!'); // 发送消息
};
// 接收消息
ws.onmessage = (event) => {
console.log('收到消息:', event.data);
};
// 连接关闭
ws.onclose = (code, reason) => {
console.log(`连接关闭: ${code}, ${reason}`);
};
二、UI组件与交互
1. TDesign for HarmonyOS(企业级UI)
腾讯 TDesign 适配 HarmonyOS 的版本,包含企业级 UI 组件,风格统一,覆盖表单、导航、数据展示等场景。
json
"dependencies": {
"@tdesign/arkui-harmonyos": "0.8.5"
}
typescript
import { Button, Dialog } from '@tdesign/arkui-harmonyos';
import { Column } from '@arkui-x/components';
@Entry
@Component
struct TDesignDemo {
@State showDialog: boolean = false;
build() {
Column() {
// primary按钮
Button({ type: 'primary', text: '打开弹窗' })
.onClick(() => this.showDialog = true)
// 弹窗组件
Dialog({
title: '提示',
content: '这是TDesign弹窗',
open: this.showDialog,
onClose: () => this.showDialog = false
})
}
.width('100%')
.padding(20)
}
}
2. ohos-calendar(日历组件)
高性能日历组件,支持日期选择、范围选择、自定义样式。
json
"dependencies": {
"@ohos/calendar": "3.2.1"
}
typescript
import { Calendar } from '@ohos/calendar';
import { Column } from '@arkui-x/components';
@Entry
@Component
struct CalendarDemo {
@State selectedDate: Date = new Date();
build() {
Column() {
Calendar({
startDate: new Date(2024, 0, 1),
endDate: new Date(2025, 11, 31),
selectedDate: this.selectedDate,
onSelect: (date) => {
this.selectedDate = date;
console.log(`选中日期: ${date.toLocaleDateString()}`);
}
})
.width('90%')
.height(400)
}
}
}
三、状态管理
1. ohos-pinia(轻量状态管理)
类似 Vue Pinia 的状态管理库,采用模块化设计,支持 TypeScript 类型推导,更简洁的 API。
json
"dependencies": {
"@ohos/pinia": "2.2.3"
}
typescript
import { createPinia, defineStore } from '@ohos/pinia';
// 1. 创建Pinia实例
const pinia = createPinia();
// 2. 定义Store
const useUserStore = defineStore('user', {
state: () => ({
name: 'HarmonyOS',
age: 3
}),
actions: {
incrementAge() {
this.age++;
}
},
getters: {
doubleAge: (state) => state.age * 2
}
});
// 3. 组件中使用
@Component
struct UserInfo {
private userStore = useUserStore(pinia);
build() {
Column() {
Text(`Name: ${this.userStore.name}`)
Text(`Age: ${this.userStore.age}`)
Text(`Double Age: ${this.userStore.doubleAge}`)
Button('增加年龄')
.onClick(() => this.userStore.incrementAge())
}
}
}
四、数据存储
1. ohos-sqlite(ORM数据库)
json
"dependencies": {
"@ohos/sqlite-orm": "4.1.0"
}
typescript
import { Database, Entity, Column, PrimaryGeneratedColumn } from '@ohos/sqlite-orm';
// 1. 定义实体类
@Entity('user')
class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
age: number;
}
// 2. 初始化数据库
const db = new Database({
name: 'myDB',
entities: [User],
version: 1
});
// 3. 数据库操作
async function dbOperations() {
const userRepo = db.getRepository(User);
// 插入数据
const newUser = new User();
newUser.name = 'Test';
newUser.age = 20;
await userRepo.save(newUser);
// 查询数据
const users = await userRepo.find();
console.log('用户列表:', users);
}
五、工具类
1. ohos-lodash(工具函数)
Lodash 的 HarmonyOS 适配版,提供字符串、数组、对象等常用工具函数(如深拷贝、防抖节流、数据格式化)。
json
"dependencies": {
"@ohos/lodash": "4.17.21"
}
typescript
import _ from '@ohos/lodash';
// 数组去重
const arr = [1, 2, 2, 3, 3, 3];
const uniqueArr = _.uniq(arr); // [1,2,3]
// 深拷贝
const obj = { a: 1, b: { c: 2 } };
const copyObj = _.cloneDeep(obj);
// 防抖函数
const debounced = _.debounce(() => {
console.log('防抖执行');
}, 500);
// 调用防抖函数(连续触发时仅最后一次生效)
debounced();
六、媒体与图形
1. ohos-glide(图片加载)
参考 Android Glide 的图片加载库,支持网络 / 本地图片加载、缓存、裁剪、圆角处理。
json
"dependencies": {
"@ohos/glide": "2.3.0"
}
typescript
import { Glide } from '@ohos/glide';
import { Image } from '@arkui-x/components';
@Component
struct ImageDemo {
build() {
Column() {
Image()
.width(300)
.height(200)
.onComplete(() => {
// 加载网络图片
Glide.with(this)
.load('https://picsum.photos/300/200')
.placeholder($r('app.media.default_img')) // 占位图
.error($r('app.media.error_img')) // 错误图
.into(this); // 绑定到当前Image组件
})
}
}
}