您现在的位置是:首页 > 编程 > 

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

2025-07-26 15:41:01
【HarmonyOS】HMRouter使用详解(四)路由拦截 路由可以对指定或全局路由跳转时添加,作用是可以实现在页面切换前做判断是否有进入当前页面的权限。这篇文章将实现登录的全局路由拦截样式。新建类通过继承IHMInterceptor接口实现生命周期接口的方法重写。 通过添加@HMInterceptor装饰器,来定义类的名称,然后在页面中使用IHMInterceptor接

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

路由


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

新建类


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

IHMInterceptor接口

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

代码语言:javascript代码运行次数:0运行复制
export interface IHMInterceptor {
    handle(info: HMInterceptorInfo): HMInterceptorAction;
}

HMInterceptorInfo参数

获取到的数据对象。

代码语言:javascript代码运行次数:0运行复制
export interface HMInterceptorInfo {
    srcame: string;
    targetame: string;
    isSrc?: boolean;
    type: HMActionType;
    routerPathInfo: HMRouterPathInfo;
    routerPathCallback?: HMRouterPathCallback;
    context: UIContext;
}
  • srcame:发起页面名称。
  • targetame:目标页面名称。
  • isSrc:是否是发起页面。
  • type:路由跳转类型,push,replace,pop。
  • routerPathInfo:路由跳转信息,HMRouterPathInfo。
  • routerPathCallback:路由跳转回调,HMRouterPathCallback。
  • context:UIContext,可以用来对UI界面进行操作。

HMInterceptorAction枚举值

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

  • DO_EXT:继续执行下一个。
  • DO_REJECT:停止执行下一个,并且不执行路由跳转动画,不执行路由栈操作。
  • DO_TRASITIO:跳过后续,直接执行路由转场动画,执行路由栈操作。
@HMInterceptor装饰器

需要标记在继承了IHMInterceptor接口的对象上,声明此对象为一个。

在路由栈发生变化前,转场动画发生前进行回调。

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

登录界面实现全局页面跳转


LoginModel

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

代码语言:javascript代码运行次数:0运行复制
@Observed
export class LoginModel {
  ame: string = "";
  Password: string = "";

  ctructor(name: string, password: string) {
    this.ame = name;
    this.Password = password;
  }
}
User

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

代码语言:javascript代码运行次数:0运行复制
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

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

代码语言:javascript代码运行次数:0运行复制
import { HMInterceptorInfo, HMRouter, HMRouterMgr } from "@hadss/hmrouter";
import { User } from "../../Common/User";

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

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

  build() {
    Column() {
      Row() {
        Text("账户:")
          .fontSize(16)
          .margin({ left: 10, right: 10 })
        TextInput({ text: this.Userame, placeholder: "请输入账户" })
          .layoutWeight(1)
          .margin({ right: 10 })
          .onChange((value) => {
            this.Userame = 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("#f1f2f")
            .fontColor("#007dfe")
            .onClick(() => {

            })

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

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

登录

代码语言:javascript代码运行次数:0运行复制
import { HMInterceptor, HMInterceptorAction, HMInterceptorInfo, HMRouterMgr, IHMInterceptor } from "@hadss/hmrouter";
import { User } from "../Common/User";

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

#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格

本文地址:http://www.dnpztj.cn/biancheng/1224249.html

相关标签:无
上传时间: 2025-07-25 21:30:11
留言与评论(共有 17 条评论)
本站网友 深度睡眠曲
0秒前 发表
HMInterceptorAction; }HMInterceptorInfo参数获取到的数据对象
本站网友 亲子分
27分钟前 发表
global
本站网友 母乳性黄疸症状
12分钟前 发表
password
本站网友 boll指标
21分钟前 发表
登录界面实现全局页面跳转LoginModel登录用的类
本站网友 分舌手术
28分钟前 发表
登录界面实现全局页面跳转LoginModel登录用的类
本站网友 seo外包
28分钟前 发表
代码语言:javascript代码运行次数:0运行复制export interface HMInterceptorInfo { srcame
本站网友 昆山自考
25分钟前 发表
不再执行下一个
本站网友 新春愉快
18分钟前 发表
不执行路由栈操作
本站网友 小儿隐睾
16分钟前 发表
targetame:目标页面名称
本站网友 侧吸式抽油烟机排名
15分钟前 发表
"请输入账户" }) .layoutWeight(1) .margin({ right
本站网友 雪里开
27分钟前 发表
数字越大优先级越高
本站网友 中国大唐
19分钟前 发表
interceptorame
本站网友 这种感觉就是爱
4分钟前 发表
type:路由跳转类型
本站网友 拷问馆
15分钟前 发表
HMInterceptorAction
本站网友 冲上
29分钟前 发表
当为false时需要配置在@HMRouter的interceptors中才生效
本站网友 中航二集团
20分钟前 发表
HMInterceptorInfo)