作者:木棉花潘颖琳
本文是关于鸿蒙 Web 组件抽奖案例(ArkTS)的学习笔记。
本文分享的案例是 Web 组件如何加载本地 H5 小程序。所加载的页面是一个由 HTML CSS Javascript 实现的完整小应用。
至于加载云端的 H5 小程序,实现步骤类似,可移步至 codelabs-Web 组件抽奖案例细览。
https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/tutorials_HarmonyOS-WebComponent-ArkTS?ha_linker=eyJ0cyI6MTY3NzczNjQ3MjAxOSwiaWQiOiJiNzBiMmI1ODVhY2M0MGY4ODJmZjExYzFhM2QxYzE2NiJ9
效果图如下:
关键知识概念
Web 组件:提供具有网页显示能力的 Web 组件。访问在线网页时需添加网络权限:ohos.permission.INTERNET。
https://developer.HarmonyOS.com/cn/docs/documentation/doc-references/ts-basic-components-web-0000001333720957?ha_linker=eyJ0cyI6MTY3NzczNjcwNTgzMSwiaWQiOiI4ZDBkZTMzZjU1MzY0NDRlYjZkYTQ5MjM1MzcwMjEzZiJ9
runJavaScript:异步执行 JavaScript 脚本,并通过回调方式返回脚本执行的结果。
runJavaScript 需要在 loadUrl 完成后,比如 onPageEnd 中调用。
runJavaScript(options: { script: string, callback?: (result: string) => void })
onConfirm:网页调用 Confirm() 告警时触发此回调。此案例是用于回显抽奖结果。
onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
创建空项目
选择 HarmonyOS 模板,项目 SDK 选择为 API9,选择模型为 Stage 模型。
如果要加载云端 H5 小程序的话,要记得在 module.json5 文件下添加网络权限:
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
],
编写本地 H5 页面
在 src/main/resources/rawfile 下分别创建:
主要代码(抽奖功能实现):
// 旋转函数
function roll() {
// 速度衰减
speed -= 50;
if (speed <= 10) {
speed = 10;
}
// 每次调用都去掉全部active类名,即去掉选中单元格的效果
for (let j = 0; j < allPrizesLi.length; j ) {
allPrizesLi[j].classList.remove('active');
}
prizesPosition ;
// 计算转圈次数,每至尾元素则圈数 1
if (prizesPosition >= allPrizesLi.length - 1) {
prizesPosition = 0;
count ;
}
//为当前选中的单元格添加active类,以添加选中的效果样式
allPrizesLi[prizesPosition].classList.add('active');
let initSpeed = 500;
let timer; //定义定时器
let totalCount = 5; // 至少转动的总圈数
// 满足转圈数和指定位置就停止
if (count >= totalCount && (prizesPosition 1) == index) {
clearTimeout(timer);
isClick = true;
speed = initSpeed;
timer = setTimeout(openDialog, 1000); // 等待1s打开弹窗
} else {
timer = setTimeout(roll, speed); // 不满足条件时调用定时器
// 最后一圈减速
if (count >= totalCount - 1 || speed <= 50) {
speed = 100;
}
}
}
// 抽奖开始函数
function startDraw() {
// 防止抽奖多次触发
if (isClick) {
count = 0;
// 随机产生中奖位置
index = Math.floor(Math.random() * prizesArr.length 1);
roll();
isClick = false;
}
}
function openDialog() {
confirm(prizesArr[prizesPosition]);
}
调用 web 组件
在 pages 文件下创建文件 MainPage 和 WebPage,其中 WebPage 用于调用 web 组件,在 MainPage 中有用到一个自定义属性,觉得蛮有用的,记录一下:
@Extend(Button) function fancy (top: string) {
.fontSize(16)
.fontColor($r('app.color.start_window_background'))
.width('86.7%')
.height('5.1%')
.margin({ top: top })
.backgroundColor($r('app.color.blue'))
.borderRadius('20')
}
Navigator({ target:'pages/WebPage', type: NavigationType.Push }) {
Button($r('app.string.loadLocalH5'))
.fancy('10%')
}
.params({ path:$rawfile('index.html'), tips: $r('app.string.local') })
}
通过 navigator 组件带参跳转至 WebPage 界面,使用 web 组件前要先创建一个 web 控制器,则添加以下代码:
webController: web_webview.WebviewController = new web_webview.WebviewController();
@State params: object = router.getParams();
其中,webviewController 要将 IDE 升级到最新版本才能用,是 API9 的接口,上述 WebController 接口在最新版本时弃用了。
同时要注意在 EntryAbility.ts 文件下修改:,也要注意查看 main_pages.json 的配置。
WebPage 中主要代码部分:
// web组件加载本地H5
Web({ src: this.params['path'], controller: this.webController })
.zoomAccess(false)
.width('93.3%')
.aspectRatio(1)
.margin({ left: '3.3%', right: '3.3%', top:'7.1%'})
.onConfirm((event) => {
alertDialog.show({
message: '恭喜您抽中' `${event.message}`,
confirm: {
value: $r('app.string.web_alert_dialog_button_value'),
action: () => {
event.result.handleConfirm();
}
},
cancel: () => {
event.result.handleCancel();
}
});
return true;
})
下方的按钮,异步执行 JavaScript 脚本 startDraw()。
Button($r('app.string.btnValue'))
.fontSize(16)
.fontColor($r('app.color.start_window_background'))
.margin({ top: '10%' })
.width('86.7%')
.height('5.1%')
.backgroundColor($r('app.color.blue'))
.borderRadius('20')
.onClick(() => {
this.webController.runJavaScript('startDraw()');
})
到此,然后就可以运行模拟器 P50 进行调试了!
,Copyright © 2008-2022 秒下下载站
m.down10s.com .All Rights Reserved