自学内容网 自学内容网

【HarmonyOS】HMRouter使用详解(四)路由拦截

路由拦截器


可以对指定或全局路由跳转时添加拦截器,作用是可以实现在页面切换前做判断是否有进入当前页面的权限。这篇文章将实现登录的全局路由拦截样式。

新建拦截器类


通过继承IHMInterceptor接口实现生命周期接口的方法重写。 通过添加@HMInterceptor装饰器,来定义拦截器类的名称,然后在页面中使用

IHMInterceptor接口

包含一个handle方法,接口拦截时,会执行当前方法。

export interface IHMInterceptor {
    handle(info: HMInterceptorInfo): HMInterceptorAction;
}

HMInterceptorInfo参数

拦截器获取到的数据对象。

export interface HMInterceptorInfo {
    srcName: string;
    targetName: string;
    isSrc?: boolean;
    type: HMActionType;
    routerPathInfo: HMRouterPathInfo;
    routerPathCallback?: HMRouterPathCallback;
    context: UIContext;
}

  • srcName:发起页面名称。
  • targetName:目标页面名称。
  • isSrc:是否是发起页面。
  • type:路由跳转类型,push,replace,pop。
  • routerPathInfo:路由跳转信息,HMRouterPathInfo。
  • routerPathCallback:路由跳转回调,HMRouterPathCallback。
  • context:UIContext,可以用来对UI界面进行操作。

HMInterceptorAction枚举值

方法的返回值,表示下一个拦截器的动作

  • DO_NEXT:继续执行下一个拦截器。
  • DO_REJECT:停止执行下一个拦截器,并且不执行路由跳转动画,不执行路由栈操作。
  • DO_TRANSITION:跳过后续拦截器,直接执行路由转场动画,执行路由栈操作。

@HMInterceptor装饰器

需要标记在继承了IHMInterceptor接口的对象上,声明此对象为一个拦截器。
在路由栈发生变化前,转场动画发生前进行回调。

  • interceptorName:拦截器名称,必填。
  • priority:拦截器优先级,数字越大优先级越高,非必填,默认为9。按照优先级顺序执行,不区分自定义或者全局拦截器,优先级相同时先执行@HMRouter中定义的自定义拦截器。当优先级一致时,先执行srcPage>targetPage>global。
  • global: 是否为全局拦截器,当配置为true时,所有跳转均过此拦截器;默认为false,当为false时需要配置在@HMRouter的interceptors中才生效。

登录界面实现全局页面跳转拦截器


LoginModel

登录用的类,这里也当作是用户类来使用了。

@Observed
export class LoginModel {
  Name: string = "";
  Password: string = "";

  constructor(name: string, password: string) {
    this.Name = name;
    this.Password = password;
  }
}

User

定义一个全局类用来实现用户的登录操作,这里没有封装后续获取用户信息的方法。

import { LoginModel } from "../Models/LoginModel";

export class User {
  private static LoginUser?: LoginModel

  /**
   * 登录
   * @param username
   * @param password
   * @returns
   */
  public static Login(username: string, password: string): string {
    if (username == undefined || username == "" || password == undefined || password == "") {
      return "登录失败";
    }
    User.LoginUser = new LoginModel(username, password);
    return "登录成功";
  }

  /**
   *登出
   */
  public static Logout() {
    User.LoginUser = undefined;
  }

  /**
   * 是否登录
   * @returns
   */
  public static IsLogin(): boolean {
    return User.LoginUser != undefined;
  }
}

LoginPage

登录界面,实现页面跳转和携带参数跳转的操作。

import { HMInterceptorInfo, HMRouter, HMRouterMgr } from "@hadss/hmrouter";
import { User } from "../../Common/User";

@HMRouter({ pageUrl: "LoginPage" })
@Component
export struct LoginPage {
  @State UserName: string = "";
  @State Password: string = "";
  TargetPath?: string;
  PathParam: ESObject;

  aboutToAppear(): void {
    let paramResult: HMInterceptorInfo = HMRouterMgr.getCurrentParam() as HMInterceptorInfo;
    if (paramResult == undefined) {
      return;
    }
    this.TargetPath = paramResult.targetName;
    this.PathParam = paramResult.routerPathInfo.param;
  }

  build() {
    Column() {
      Row() {
        Text("账户:")
          .fontSize(16)
          .margin({ left: 10, right: 10 })
        TextInput({ text: this.UserName, placeholder: "请输入账户" })
          .layoutWeight(1)
          .margin({ right: 10 })
          .onChange((value) => {
            this.UserName = value
          })
      }
      .width("100%")

      Row() {
        Text("密码:")
          .fontSize(16)
          .margin({ left: 10, right: 10 })
        TextInput({ text: this.Password, placeholder: "请输入密码" })
          .layoutWeight(1)
          .margin({ right: 10 })
          .type(InputType.Password)
          .onChange((value) => {
            this.Password = value
          })
      }
      .width("100%")
      .margin({ top: 20 })

      Grid() {
        GridItem() {
          Button("注册")
            .width("100%")
            .backgroundColor("#f1f2f3")
            .fontColor("#007dfe")
            .onClick(() => {

            })

        }
        .width("50%")
        .padding({ right: 10, left: 10 })

        GridItem() {
          Button("登录")
            .width("100%")
            .onClick(() => {
              let loginResult: string = User.Login(this.UserName, this.Password);
              if (loginResult === "登录成功") {
                HMRouterMgr.replace({
                  pageUrl: this.TargetPath,
                  param: this.PathParam
                })
              }
              console.info("登录结果:" + loginResult);
            })
        }
        .width("50%")
        .padding({ right: 10, left: 10 })
      }
      .rowsTemplate("1tf 1tf")
      .margin({ top: 10 })
      .width("100%")
      .height(60)
    }
    .width("100%")
    .height("100%")
  }
}

LoginInterceptor

登录拦截器

import { HMInterceptor, HMInterceptorAction, HMInterceptorInfo, HMRouterMgr, IHMInterceptor } from "@hadss/hmrouter";
import { User } from "../Common/User";

@HMInterceptor({
  priority: 9,
  interceptorName: "LoginInterceptor",
  global: true
})
export class LoginInterceptor implements IHMInterceptor {
  handle(info: HMInterceptorInfo): HMInterceptorAction {
    if (User.IsLogin()) {
      // 跳转下一个拦截器处理
      return HMInterceptorAction.DO_NEXT;
    } else {
      HMRouterMgr.push({
        pageUrl: 'LoginPage',
        skipAllInterceptor: true
      })
      // 拦截结束,不再执行下一个拦截器,不再执行相关转场和路由栈操作
      return HMInterceptorAction.DO_REJECT;
    }
  }
}

实现效果如下


原文地址:https://blog.csdn.net/Oneal5354/article/details/142861722

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!