首页 > 解决方案 > XML 视图的 SapUI5 路由器问题

问题描述

我正在开发一个简单的 UI5 项目,能够了解路由器的工作原理。在这个过程中,我遇到了与路由器事件相关的问题。我有三个 XML 视图,它们的名称分别是 FirstPage、SecondPage 和 ThirdPage。ThirdPage 在其他两个页面中实现,如下代码;

<mvc:XMLView viewName="SapUI5Tutorial.Application.Main.views.ThirdPage.view.ThirdPage"/>

例如 FirstPage.xml

<mvc:View displayBlock="true" controllerName="SapUI5Tutorial.Application.Main.views.FirstPage.controller.FirstPage"
xmlns:mvc="sap.ui.core.mvc"
xmlns:core="sap.ui.core"
xmlns:l="sap.ui.layout"
xmlns="sap.m" height="100%">
<Page title="First Page" class="sapUiNoContentPadding">
    <subHeader>
        <Toolbar>
            <VBox width="100%" alignItems="Center">
                <Button text="Second Page Link" press="handleNavSecondPage"/>
            </VBox>
        </Toolbar>
    </subHeader>
    <mvc:XMLView viewName="SapUI5Tutorial.Application.Main.views.ThirdPage.view.ThirdPage"/>
</Page>

当我单击“第二页链接”按钮时,我正在导航到 SecondPage。但是ThirdPage是由于SecondPage里面ThirdPage的Router函数运行了两次

ThirdPage 的控制器;

sap.ui.define([
"sap/ui/core/mvc/Controller",
], function (Controller, FragmentController) {
"use strict";
var base, oRouter;
return Controller.extend("SapUI5Tutorial.Application.Main.views.ThirdPage", {
    onInit: function () {
        base = this;
        base.getView().setModel(oModel);
        oRouter = sap.ui.core.UIComponent.getRouterFor(base);
        oRouter.getRoute("FirstPage").attachMatched(base.firstPagePatternMatched, base);
        oRouter.getRoute("SecondPage").attachMatched(base.secondPagePatternMatched, base);
    },
    firstPagePatternMatched: function (oEvent) {
        console.log(oEvent)
    },
    secondPagePatternMatched: function (oEvent) {
        //Due to the third page is used for inside two other pages (FirstPage and SecondPage) this function is running twice
        console.log(oEvent)
    }
});

});

如何防止运行 ThirdPage 的 Router 事件两次?谢谢你的帮助

标签: sapui5

解决方案


我相信你的问题是使用.attachMatched而不是.attachPatternMatched

前者针对任何路由或子路由触发,而后者仅针对子路由触发。

文档对此不是很清楚,但可以在此处找到。


推荐阅读