You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic Core使用ion-router路由时如何向根导航页面传递参数

原生JS配合Ionic ion-router向根页面传参的解决方案

当使用ion-router接管路由逻辑时,ion-nav的rootParams配置会被路由的加载逻辑覆盖,因此需要通过以下几种方式实现根页面传参:

方案1:监听路由事件注入参数

原理是ion-router触发路由变更事件时,会暴露即将加载的路由信息,等待组件实例初始化完成后直接挂载参数即可,和原有rootParams的效果完全一致。

const nav = document.querySelector('ion-nav');
const router = document.querySelector('ion-router');

// 全局要传递的根参数
const rootParams = { a: 1, b: 2 };

// 监听路由即将变更事件
router.addEventListener('ionRouteWillChange', (e) => {
  // 判断当前跳转的是根路径的new-page组件
  if (e.detail.to === '/' && e.detail.component === 'new-page') {
    // 等待组件注册完成后赋值
    customElements.whenDefined('new-page').then(() => {
      const pageInstance = document.querySelector('new-page');
      if (pageInstance) {
        Object.assign(pageInstance, rootParams);
      }
    });
  }
});

// 原有页面组件定义无需修改
class NewPage extends HTMLElement {
  async connectedCallback() {
    this.innerHTML = `
      <ion-header class='gallery-page' translucent>
        <ion-toolbar>
          <ion-buttons slot="start">
            <ion-back-button />
          </ion-buttons>
          <ion-title>Root Page</ion-title>
        </ion-toolbar>
      </ion-header>
      <ion-content fullscreen class="ion-padding">
       a: ${this.a}, b: ${this.b}
       <br />
       <ion-button>New Page</ion-button>
      </ion-content>
    `;
    const btn = this.querySelector('ion-button');
    btn.addEventListener('click', () => {
        nav.push('new-page', { a: this.a + 1, b: this.b + 1});
    })
  }
}
customElements.define('new-page', NewPage);

方案2:全局状态托管参数

如果参数需要在多页面复用,可以把参数存在全局可访问的对象中,页面初始化时直接读取即可:

// 全局状态对象,可放在全局作用域或者单独的配置模块中
window.AppState = {
  rootParams: { a: 1, b: 2 }
};

class NewPage extends HTMLElement {
  async connectedCallback() {
    // 直接从全局状态读取参数
    const { a, b } = window.AppState.rootParams;
    this.innerHTML = `
      <ion-header class='gallery-page' translucent>
        <ion-toolbar>
          <ion-buttons slot="start">
            <ion-back-button />
          </ion-buttons>
          <ion-title>Root Page</ion-title>
        </ion-toolbar>
      </ion-header>
      <ion-content fullscreen class="ion-padding">
       a: ${a}, b: ${b}
       <br />
       <ion-button>New Page</ion-button>
      </ion-content>
    `;
  }
}
customElements.define('new-page', NewPage);

方案3:路由查询参数传递(适合公开参数)

如果参数不需要保密,可以直接拼接在根路由的URL上,页面加载时解析URL参数即可:

class NewPage extends HTMLElement {
  async connectedCallback() {
    // 解析URL查询参数
    const urlParams = new URLSearchParams(window.location.search);
    const a = Number(urlParams.get('a')) || 1;
    const b = Number(urlParams.get('b')) || 2;
    this.innerHTML = `
      <!-- 页面渲染逻辑和之前一致 -->
    `;
  }
}
// 应用初始访问时地址为 /?a=1&b=2 即可完成参数传递

内容的提问来源于stack exchange,提问作者Dave F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:36:03