完整的使用指南,帮助你快速上手 QuickBox 框架和组件库
npm install quickbox
# 或
yarn add quickbox
# 或
pnpm add quickbox// 方式1:默认导入(推荐)
import QuickBox from 'quickbox';
// 方式2:按需导入
import { Request, Storage, Router } from 'quickbox';
// 方式3:导入工具函数
import { debounce, throttle, formatSeconds } from 'quickbox';<!-- 在 script 标签中 -->
<script>
import QuickBox from 'quickbox';
export default {
async onInit() {
const info = await QuickBox.getSystemInfo();
console.log('当前厂商:', info.brand);
}
};
</script>QuickBox 开箱即用,无需任何配置即可开始使用:
import QuickBox from 'quickbox';
// 立即使用,无需初始化
const info = await QuickBox.getSystemInfo();
console.log('当前厂商:', info.brand);import QuickBox from 'quickbox';
// GET 请求
const users = await QuickBox.get('https://api.example.com/users', { page: 1 });
// POST 请求
const result = await QuickBox.post('https://api.example.com/users', {
name: 'John',
email: 'john@example.com'
});
// PUT 请求
await QuickBox.put('https://api.example.com/users/1', { name: 'Jane' });
// DELETE 请求
await QuickBox.delete('https://api.example.com/users/1');
// 使用 Request 类(支持拦截器)
QuickBox.Request.configure({
baseURL: 'https://api.example.com',
timeout: 10000,
baseParams: { token: 'xxx' }
});// 设置存储
await QuickBox.setStorage('user', { id: 1, name: 'John' });
// 获取存储
const user = await QuickBox.getStorage('user');
// 删除存储
await QuickBox.removeStorage('user');
// 清除所有存储
await QuickBox.Storage.clear();// 跳转到页面
QuickBox.navigateTo({
uri: '/pages/detail',
params: { id: 1, name: 'John' }
});
// 返回上一页
QuickBox.navigateBack();
// 重定向(替换当前页面)
QuickBox.redirectTo({ uri: '/pages/login' });
// 返回首页(自动适配各厂商差异)
QuickBox.navigateToHome();
// 获取当前路由状态
const state = QuickBox.getRouterState();
console.log('当前路径:', state.path);
console.log('页面参数:', state.params);// 获取系统信息
const info = await QuickBox.getSystemInfo();
console.log('品牌:', info.brand);
console.log('型号:', info.model);
console.log('系统版本:', info.system);
// 获取厂商信息
const vendorInfo = QuickBox.getVendorInfo();
console.log('厂商:', vendorInfo.vendor);
console.log('框架版本:', vendorInfo.version);
// 能力检测
if (QuickBox.canIUse('payment')) {
// 使用支付功能
}
// 厂商检测
if (QuickBox.isXiaomi()) {
console.log('当前是小米设备');
}
if (QuickBox.isHuaweiGroup()) {
console.log('当前是华为系设备(华为或荣耀)');
}// Toast 提示
QuickBox.showToast('操作成功');
QuickBox.showToast({ message: '加载中...', duration: 2000 });
// 对话框
const result = await QuickBox.showDialog({
title: '提示',
content: '确定要删除吗?',
buttons: [
{ text: '取消', color: '#999' },
{ text: '确定', color: '#007AFF' }
]
});
if (result.index === 1) {
console.log('用户点击了确定');
}
// 操作菜单
const index = await QuickBox.showActionMenu({
itemList: ['拍照', '从相册选择', '取消']
});
// Loading
QuickBox.showLoading({ message: '加载中...' });
// ... 执行操作
QuickBox.hideLoading();// 获取设备详细信息
const deviceInfo = await QuickBox.getDeviceInfo();
// 获取设备ID
const deviceId = await QuickBox.getDeviceUserId();
// 获取OAID
const oaid = await QuickBox.getDeviceOAID();
// 同时获取设备ID和OAID
const ids = await QuickBox.getDeviceIds();
// 获取完整信息(包括设备ID和OAID)
const fullInfo = await QuickBox.Device.getFullInfo();QuickBox 提供了丰富的开箱即用组件,详细文档请查看 组件库文档。
<!-- 在 template 中引入组件 -->
<import name="VideoPlayer" src="quickbox/components/VideoPlayer"></import>
<import name="Dialog" src="quickbox/components/Dialog"></import>
<import name="Loading" src="quickbox/components/Loading"></import><template>
<VideoPlayer
video-id="video_1"
video-url="{{videoUrl}}"
cover-image="{{coverImage}}"
video-info="{{videoInfo}}"
content-info="{{contentInfo}}"
follow-status="{{followStatus}}"
autoplay="{{true}}"
initial-time="{{playedSeconds}}"
onplay="onPlay"
onpause="onPause"
onfinish="onFinish"
onerror="onError"
onshow-section="onShowSection"
onlike="onLike"
onfollow="onFollow"
/>
</template>
<script>
import VideoPlayer from 'quickbox/components/VideoPlayer';
export default {
components: {
VideoPlayer
},
data: {
videoUrl: 'https://example.com/video.mp4',
coverImage: '/path/to/cover.jpg',
videoInfo: {
contentChapterName: '第1集',
playerUrlInfo: 'https://example.com/video.mp4'
},
contentInfo: {
contentName: '视频标题',
likeCount: 1000,
likeStatus: false
},
followStatus: false,
playedSeconds: 0
},
onPlay({ detail }) {
console.log('开始播放');
},
onPause({ detail }) {
console.log('暂停播放');
}
};
</script><template>
<Reader
content-id="{{contentId}}"
current-chapter-id="{{chapterId}}"
chapter-name="{{chapterName}}"
content="{{content}}"
prev-chapter-id="{{prevChapterId}}"
next-chapter-id="{{nextChapterId}}"
read-type="{{readType}}"
config="{{readerConfig}}"
onback="goBack"
onselect-chapter="onSelectChapter"
onprev-chapter="onPrevChapter"
onnext-chapter="onNextChapter"
/>
</template>
<script>
import Reader from 'quickbox/components/Reader';
export default {
components: {
Reader
},
data: {
contentId: 'book_1',
chapterId: 'chapter_1',
chapterName: '第一章',
content: ['段落1', '段落2', '段落3'],
readType: 'vertical',
readerConfig: {
fontSize: 30,
bgColor: '#ffffff',
textColor: '#333333',
theme: 'default'
}
}
};
</script><!-- Dialog 弹窗 -->
<Dialog
is-show="{{showDialog}}"
title="提示"
message="确定要删除吗?"
buttons="{{[
{ text: '取消', color: '#999' },
{ text: '确定', color: '#007AFF', primary: true }
]}}"
onbutton-click="onDialogButtonClick"
onclose="onDialogClose"
/>
<!-- Loading 加载 -->
<Loading message="加载中..." className="fullscreen" />
<!-- Empty 空状态 -->
<Empty
message="暂无内容"
show-image="{{true}}"
show-button="{{true}}"
button-text="去查看"
onbutton-click="onEmptyButtonClick"
/>
<!-- GridList 网格列表 -->
<GridList
title="推荐内容"
list="{{videoList}}"
columns="{{2}}"
loading="{{loading}}"
has-more="{{hasMore}}"
onload-more="onLoadMore"
onitem-click="onItemClick"
/><!-- PageTitleBar 页面标题栏 -->
<PageTitleBar
title="我的页面"
show-action="{{true}}"
action-image="/assets/newImages/base/icon.png"
onaction-click="onActionClick"
/>
<!-- BackButton 返回按钮 -->
<BackButton
icon="/assets/newImages/base/back.png"
text="返回"
use-router="{{true}}"
onback-click="onBackClick"
/>
<!-- Card 卡片 -->
<Card
title="卡片标题"
content="卡片内容"
clickable="{{true}}"
oncard-click="onCardClick"
/><!-- AddDesktop 添加桌面引导 -->
<AddDesktop
is-show="{{showAddDesktop}}"
image="{{desktopImage}}"
button-text="添加本剧到桌面,方便下次观看"
onadd-success="onAddSuccess"
/>
<!-- ShareButton 分享按钮 -->
<ShareButton
title="分享标题"
summary="分享摘要"
image-path="/assets/newImages/base/coin.png"
target-url="https://example.com"
platforms="{{['WEIXIN', 'WEIBO']}}"
onshare-success="onShareSuccess"
/>更多组件使用示例请查看 组件库示例文档。
// 统一支付接口(自动识别厂商)
const result = await QuickBox.vendorPay(
'ORDER_123', // 订单号
10000, // 金额(分)
'商品描述', // 商品描述
'MEMBER_ID' // 会员ID(小米支付需要)
);
if (result.status === 'success') {
console.log('支付成功');
}
// 厂商特定支付
// 华为支付
await QuickBox.huaweiPay({
orderInfo: 'ORDER_123',
productId: 'PRODUCT_123',
applicationID: 'APP_ID',
publicKey: 'PUBLIC_KEY'
});
// 小米支付(自动处理登录)
await QuickBox.xiaomiPay({
orderId: 'ORDER_123',
price: 10000,
purchaseName: '商品名称',
memberId: 'MEMBER_ID'
});
// OPPO支付
await QuickBox.oppoPay({
orderInfo: 'ORDER_123',
prePayToken: 'TOKEN',
detailCode: 'DETAIL_CODE'
});
// vivo支付
await QuickBox.vivoPay({
orderInfo: 'ORDER_123',
payInfoParams: { /* ... */ }
});// 统一登录接口(小米)
const loginResult = await QuickBox.login('YOUR_MEMBER_ID');
if (loginResult.status === 'success') {
console.log('登录成功,openId:', loginResult.openId);
}
// 华为授权
const authResult = await QuickBox.huaweiAuthorize({
appid: 'YOUR_APPID',
scope: 'scope.baseProfile'
});// 检查广告支持
if (QuickBox.canIUseAd('rewardedVideo')) {
// 创建激励视频广告
const rewardedVideoAd = QuickBox.createRewardedVideoAd({
adUnitId: 'YOUR_AD_UNIT_ID'
});
// 加载广告
await rewardedVideoAd.load();
// 监听关闭事件
rewardedVideoAd.onClose((res) => {
if (res.isEnded) {
console.log('观看完成,发放奖励');
}
// 重新加载
rewardedVideoAd.load();
});
// 显示广告
await rewardedVideoAd.show();
}
// Banner广告
const bannerAd = QuickBox.createBannerAd({
adUnitId: 'YOUR_BANNER_AD_UNIT_ID',
style: {
left: 0,
top: 100,
width: 750,
height: 100
}
});
bannerAd.onLoad(() => {
console.log('Banner广告加载成功');
bannerAd.show();
});
// 插屏广告
const interstitialAd = QuickBox.createInterstitialAd({
adUnitId: 'YOUR_INTERSTITIAL_AD_UNIT_ID'
});
await interstitialAd.load();
await interstitialAd.show();
// 原生广告
const nativeAd = QuickBox.createNativeAd({
adUnitId: 'YOUR_NATIVE_AD_UNIT_ID',
adCount: 3 // OPPO必传
});
if (nativeAd) {
nativeAd.onLoad((data) => {
console.log('原生广告数据:', data);
// 上报曝光
nativeAd.reportAdShow({ adId: data.adId });
});
nativeAd.load();
}// 配置全局请求
QuickBox.Request.configure({
baseURL: 'https://api.example.com',
timeout: 10000,
baseParams: {
appId: 'YOUR_APP_ID',
version: '1.0.0'
},
showErrorToast: true,
onUnauthorized: async () => {
// 401时自动处理
await QuickBox.login('MEMBER_ID');
}
});
// 添加请求拦截器
QuickBox.Request.addRequestInterceptor((options) => {
// 添加token
options.header = {
...options.header,
Authorization: `Bearer ${token}`
};
return options;
});
// 添加响应拦截器
QuickBox.Request.addResponseInterceptor((response) => {
// 统一处理响应
if (response.code === 0) {
return response.data;
}
throw new Error(response.message);
});
// 添加错误拦截器
QuickBox.Request.addErrorInterceptor((error) => {
console.error('请求错误:', error);
// 可以在这里统一处理错误
return error;
});// 获取缓存的Token
const token = await QuickBox.TokenManager.getCachedToken('huawei_token');
// 缓存Token
await QuickBox.TokenManager.cacheToken('huawei_token', 'TOKEN_VALUE', 3600);
// 获取华为Token(自动缓存)
const huaweiToken = await QuickBox.TokenManager.getHuaweiToken('APP_ID', 'MEMBER_ID');
// 获取小米Token(自动缓存)
const xiaomiToken = await QuickBox.TokenManager.getXiaomiToken('MEMBER_ID');
// 根据厂商自动获取Token
const token = await QuickBox.TokenManager.getTokenByVendor({
huaweiAppid: 'APP_ID',
xiaomiMemberId: 'MEMBER_ID'
});// 标记应用已就绪
QuickBox.AppStateManager.setReady(true);
// 等待应用就绪
await QuickBox.AppStateManager.waitForReady(5000);
// 确保应用就绪后执行
const result = await QuickBox.AppStateManager.ensureReady(async () => {
return await QuickBox.get('https://api.example.com/data');
});// 设置来源(7天过期)
await QuickBox.SourceTracker.setSource(
'CONTENT_ID',
'origin_name',
'source_value',
7 // 7天过期
);
// 获取来源
const source = await QuickBox.SourceTracker.getSource('CONTENT_ID', 'origin_name');
// 检查来源是否有效
const isValid = await QuickBox.SourceTracker.isSourceValid('CONTENT_ID', 'origin_name');
// 获取所有来源
const allSources = await QuickBox.SourceTracker.getAllSources('CONTENT_ID');// 检查是否已添加到桌面
const isInstalled = await QuickBox.ShortcutUtils.checkInstalled();
if (!isInstalled) {
// 添加到桌面
const success = await QuickBox.ShortcutUtils.install({
message: '添加到桌面,方便下次使用'
});
if (success) {
QuickBox.showToast('已添加到桌面');
}
}// 获取华为支付配置
const huaweiConfig = await QuickBox.ConfigManager.getHuaweiConfig('https://api.example.com/config/huawei');
// 获取小米支付配置
const xiaomiConfig = await QuickBox.ConfigManager.getXiaomiConfig('https://api.example.com/config/xiaomi');
// 根据厂商自动获取配置
const config = await QuickBox.ConfigManager.getConfigByVendor({
huawei: 'https://api.example.com/config/huawei',
xiaomi: 'https://api.example.com/config/xiaomi',
oppo: 'https://api.example.com/config/oppo',
vivo: 'https://api.example.com/config/vivo'
});// 获取设备信息
const deviceInfo = await QuickBox.getSystemInfo();
// 内容分页
const result = QuickBox.ReaderUtils.splitContentIntoPages({
deviceInfo: {
windowWidth: deviceInfo.windowWidth,
windowHeight: deviceInfo.windowHeight,
screenDensity: deviceInfo.screenDensity
},
content: ['段落1', '段落2', '段落3'],
fontSize: 30,
lineHeightRatio: 2.1,
padding: 30,
topPadding: 100
});
// 插入广告页
const pagesWithAd = QuickBox.ReaderUtils.insertAdPages(
result.pages,
'AD_PAGE_MARKER',
0, // 第一页索引
5, // 每5页插入一个广告
true // 第一页前也插入
);
// 计算Banner样式
const bannerStyle = QuickBox.ReaderUtils.calculateBannerStyle(deviceInfo, {
height: 57,
bottom: 20,
isHuaweiGroup: QuickBox.isHuaweiGroup()
});
// 格式化阅读时间
const timeStr = QuickBox.ReaderUtils.formatReadTime(3661); // "1小时1分1秒"
// 计算阅读进度
const progress = QuickBox.ReaderUtils.calculateProgress(5, 20); // 25(25%)// 分享
await QuickBox.shareLink('https://example.com');
await QuickBox.shareText('分享内容');
// 剪贴板
await QuickBox.setClipboard('要复制的内容');
const text = await QuickBox.getClipboard();
// WebView
QuickBox.loadWebView({ url: 'https://example.com' });
// 推送
if (QuickBox.Push.isSupported()) {
const result = await QuickBox.subscribePush();
console.log('推送regId:', result.regId);
}
// 日历
await QuickBox.insertCalendar({
title: '签到提醒',
startDate: new Date('2024-01-01 20:00').getTime(),
endDate: new Date('2024-01-01 21:00').getTime(),
duration: 'PT1H',
remindMinutes: [0, 5],
rrule: 'FREQ=DAILY'
});
// 应用信息
const appInfo = await QuickBox.getAppInfo();
console.log('包名:', appInfo.packageName);
console.log('版本:', appInfo.versionName);
// 网络状态
const networkInfo = await QuickBox.getNetworkType();
console.log('网络类型:', networkInfo.type);
// 监听网络变化
const unsubscribe = QuickBox.subscribeNetwork((info) => {
console.log('网络状态变化:', info.type);
});// 防抖
const debouncedSearch = QuickBox.debounce((keyword) => {
console.log('搜索:', keyword);
}, 300);
// 节流
const throttledScroll = QuickBox.throttle(() => {
console.log('滚动');
}, 100);
// 延迟
await QuickBox.delay(1000);
// 重试
const result = await QuickBox.retry(
() => QuickBox.get('/api/data'),
3, // 最多重试3次
1000 // 每次重试间隔1秒
);
// 格式化文件大小
const size = QuickBox.formatFileSize(1024); // "1 KB"
// 深拷贝
const cloned = QuickBox.deepClone(obj);
// URL拼接
const url = QuickBox.queryString('https://example.com', { id: 1, name: 'test' });
// 格式化时间
const time = QuickBox.formatSeconds(3661); // { hours: "01", minutes: "01", seconds: "01" }
// 日期工具
const today = QuickBox.getDate(); // "2024-01-15"
const beforeDate = QuickBox.getBeforeDate('2024-01-15', 5); // "2024-01-10"
const isToday = QuickBox.checkToday('2024-01-15');
// 数字递增动画
QuickBox.countUp({
startValue: 0,
targetValue: 100,
duration: 1500,
onUpdate: (value) => console.log(value),
onComplete: () => console.log('完成')
});
// 数组查找
const label = QuickBox.valueToLabel(1, [
{ value: 1, label: '选项1' },
{ value: 2, label: '选项2' }
]);// 在 app.ux 中配置
import QuickBox from 'quickbox';
// 配置请求
QuickBox.Request.configure({
baseURL: 'https://api.example.com',
baseParams: {
appId: 'YOUR_APP_ID',
version: '1.0.0'
},
showErrorToast: true
});
// 标记应用就绪
QuickBox.AppStateManager.setReady(true);try {
const result = await QuickBox.vendorPay('ORDER_123', 10000, '商品', 'MEMBER_ID');
if (result.status === 'success') {
// 支付成功
}
} catch (error) {
console.error('支付失败:', error);
QuickBox.showToast('支付失败,请稍后重试');
}// 使用前先检测能力
if (QuickBox.canIUseAd('rewardedVideo')) {
// 使用激励视频广告
} else {
// 降级方案
QuickBox.showToast('当前设备不支持激励视频广告');
}if (QuickBox.isXiaomi()) {
// 小米特定逻辑
} else if (QuickBox.isHuaweiGroup()) {
// 华为系特定逻辑
}<!-- 1. 按需引入组件,避免不必要的加载 -->
<import name="VideoPlayer" src="quickbox/components/VideoPlayer"></import>
<!-- 2. 使用条件渲染优化性能 -->
<VideoPlayer
if="{{showVideo}}"
video-url="{{videoUrl}}"
/>
<!-- 3. 合理使用插槽自定义内容 -->
<Dialog is-show="{{showDialog}}">
<div slot="content">
<!-- 自定义内容 -->
</div>
</Dialog>
<!-- 4. 监听组件事件处理业务逻辑 -->
<VideoPlayer
onplay="onVideoPlay"
onpause="onVideoPause"
onerror="onVideoError"
/>// 1. 使用防抖节流优化频繁操作
const debouncedSearch = QuickBox.debounce((keyword) => {
// 搜索逻辑
}, 300);
// 2. 合理使用缓存
const cachedToken = await QuickBox.TokenManager.getCachedToken('token_key');
if (cachedToken) {
// 使用缓存的token
} else {
// 重新获取token
}
// 3. 批量操作使用 Promise.all
const [userInfo, config, list] = await Promise.all([
QuickBox.get('/api/user'),
QuickBox.get('/api/config'),
QuickBox.get('/api/list')
]);A: 不需要。QuickBox 开箱即用,安装后即可直接使用。
A: 使用 QuickBox.Request.configure() 方法:
QuickBox.Request.configure({
baseURL: 'https://api.example.com'
});A: 检查返回的 result.status 和 result.message:
const result = await QuickBox.vendorPay(...);
if (result.status === 'fail') {
console.error('支付失败:', result.message);
}A: 使用厂商检测方法:
if (QuickBox.isXiaomi()) { /* 小米 */ }
if (QuickBox.isOppo()) { /* OPPO */ }
if (QuickBox.isHuaweiGroup()) { /* 华为或荣耀 */ }A: 监听错误事件:
rewardedVideoAd.onError((err) => {
console.error('广告加载失败:', err);
// 降级处理
});A: 所有组件都支持通过 class 和 style 属性自定义样式:
<VideoPlayer
video-url="{{videoUrl}}"
class="custom-video-player"
style="width: 750px; height: 500px;"
/>A: 使用相对路径引入组件:
<!-- 如果 quickbox 安装在 node_modules -->
<import name="VideoPlayer" src="quickbox/components/VideoPlayer"></import>
<!-- 或者使用绝对路径 -->
<import name="VideoPlayer" src="/node_modules/quickbox/components/VideoPlayer"></import>A: 所有组件事件使用 on 前缀:
<VideoPlayer
onplay="onPlay"
onpause="onPause"
onerror="onError"
/>A: 参考 组件库示例文档 中的组合使用示例。
详细的 API 文档请参考:
查看 CHANGELOG.md 了解版本更新内容。
Happy Coding! 🎉