HarmonyOS鸿蒙Next中使用createSubWindow传递参数问题

HarmonyOS鸿蒙Next中使用createSubWindow传递参数问题 在app中有场景使用 window.WindowStagecreateSubWindow 的回调中,调用子 WindowsetUiContent 加载子window的时候,如何传递参数? 虽能过使用 createSubWindo

3 回复

可以使用loadContent(path: string, storage: LocalStorage)方法加载新页面并通过localStorage传递参数,在新页面中通过localStorage.getShared()获取传入的localStorage。参考文档如下:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-window-0000001820880785#ZH-CN_TOPIC_0000001820880785__loadcontent9

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-localstorage-0000001820879593

// EntryAbility.ets
onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    windowStage.loadContent('pages/Index', (err) => {
        if (err.code) {
            hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
            return;
        }
        hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
        // 给Index页面传递windowStage
        AppStorage.setOrCreate('windowStage', windowStage);
    });
}
// Index.ets
import window from '@ohos.window';
import { BusinessError } from '@ohos.base';

let windowStage_: window.WindowStage | undefined = undefined;
let sub_windowClass: window.Window | undefined = undefined;

@Entry
@Component
struct Index {
    @State message: string = 'Hello World';
    storage: LocalStorage = new LocalStorage();

    private CreateSubWindow(){
        // 获取windowStage
        windowStage_ = AppStorage.get('windowStage');
        // 1.创建应用子窗口。
        if (windowStage_ == null) {
            console.error('Failed to create the subwindow. Cause: windowStage_ is null');
        } else {
            windowStage_.createSubWindow("mySubWindow", (err: BusinessError, data) => {
                let errCode: number = err.code;
                if (errCode) {
                    console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err));
                    return;
                }
                sub_windowClass = data;
                console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data));
                // 2.子窗口创建成功后,设置子窗口的位置、大小及相关属性等。
                sub_windowClass.moveWindowTo(300, 300, (err: BusinessError) => {
                    let errCode: number = err.code;
                    if (errCode) {
                        console.error('Failed to move the window. Cause:' + JSON.stringify(err));
                        return;
                    }
                    console.info('Succeeded in moving the window.');
                });
                sub_windowClass.resize(500, 500, (err: BusinessError) => {
                    let errCode: number = err.code;
                    if (errCode) {
                        console.error('Failed to change the window size. Cause:' + JSON.stringify(err));
                        return;
                    }
                    console.info('Succeeded in changing the window size.');
                });
                // 3.为子窗口加载对应的目标页面。
                this.storage.setOrCreate('storageSimpleProp', 121);
                sub_windowClass.loadContent("pages/SubWindow", this.storage, (err: BusinessError) => {
                    let errCode: number = err.code;
                    if (errCode) {
                        console.error('Failed to load the content. Cause:' + JSON.stringify(err));
                        return;
                    }
                    console.info('Succeeded in loading the content.');
                    // 3.显示子窗口。
                    (sub_windowClass as window.Window).showWindow((err: BusinessError) => {
                        let errCode: number = err.code;
                        if (errCode) {
                            console.error('Failed to show the window. Cause: ' + JSON.stringify(err));
                            return;
                        }
                        console.info('Succeeded in showing the window.');
                    });
                });
            });
        }
    }

    private destroySubWindow(){
        // 4.销毁子窗口。当不再需要子窗口时,可根据具体实现逻辑,使用destroy对其进行销毁。
        (sub_windowClass as window.Window).destroyWindow((err: BusinessError) => {
            let errCode: number = err.code;
            if (errCode) {
                console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err));
                return;
            }
            console.info('Succeeded in destroying the window.');
        });
    }

    build() {
        Row() {
            Column() {
                Text(this.message)
                .fontSize(50)
                .fontWeight(FontWeight.Bold)
                Button(){
                    Text('CreateSubWindow')
                    .fontSize(24)
                    .fontWeight(FontWeight.Normal)
                }.width(220).height(68)
                .margin({left:10, top:60})
                .onClick(() => {
                    this.CreateSubWindow()
                })
                Button(){
                    Text('destroySubWindow')
                    .fontSize(24)
                    .fontWeight(FontWeight.Normal)
                }.width(220).height(68)
                .margin({left:10, top:60})
                .onClick(() => {
                    this.destroySubWindow()
                })
                Image($rawfile('[library2].mmm.png'))
            }
            .width('100%')
        }
        .height('100%')
    }
}

更多关于HarmonyOS鸿蒙Next中使用createSubWindow传递参数问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,使用createSubWindow创建子窗口时,传递参数可以通过AbilityContextstartAbility方法实现。具体步骤如下:

  1. 定义参数:在主窗口中定义需要传递的参数,通常使用Intent对象来封装参数。
  2. 启动子窗口:通过AbilityContextstartAbility方法启动子窗口,并将Intent对象作为参数传递。
  3. 接收参数:在子窗口的onStart方法中,通过getIntent方法获取传递过来的Intent对象,并从中解析出参数。

示例代码如下:

// 主窗口代码
let intent = {
    bundleName: "com.example.subwindow",
    abilityName: "SubWindowAbility",
    parameters: {
        key1: "value1",
        key2: "value2"
    }
};
this.context.startAbility(intent);

// 子窗口代码
onStart() {
    let intent = this.context.getIntent();
    let parameters = intent.parameters;
    let value1 = parameters.key1;
    let value2 = parameters.key2;
}

通过这种方式,可以在HarmonyOS鸿蒙Next中实现主窗口与子窗口之间的参数传递。

在HarmonyOS鸿蒙Next中,使用createSubWindow创建子窗口时,可以通过windowStage.loadContent方法传递参数。具体步骤如下:

  1. 在主窗口中创建子窗口:

    let subWindow = await window.createSubWindow("subWindow");
    
  2. 在子窗口的onWindowStageCreate生命周期中,通过windowStage.loadContent传递参数:

    onWindowStageCreate(windowStage) {
        windowStage.loadContent("pages/index", { param: "value" });
    }
    
  3. 在子窗口的页面中,通过this.$datathis.$route获取传递的参数:

    let param = this.$route.param;
    

这样即可实现参数的传递与接收。

回到顶部