在Aurelia中使用路由器时如何设置/读取查询字符串

How do I set/read a query string when using the router in aurelia?

本文关键字:设置 读取 字符串 查询 何设置 Aurelia 路由器      更新时间:2023-09-26

使用 aurelia.io 框架路由器时,读取和设置查询字符串的首选方法是什么?

例如,在网址中:http://www.myapp.com/#/myroute1/?s=mystate

如何读取和设置 url 的?s=mystate部分,并让 aurelia 路由器正确导航并记住该状态,以便每当我到达route1视图模型时,我都可以读取该状态变量并对其进行处理?

在视图模型上,您可以实现方法激活(params,routeConfig),对象参数应包含查询变量

activate(params, routeConfig){
 console.log(params.s); //should print mystate
}

要导航到某个路由,您必须在应用程序中指定此路由的名称.js(名称:"重定向")

 config.map([
      { route: ['','welcome'],  moduleId: './welcome',      nav: true, title:'Welcome' },
      { route: 'flickr',        moduleId: './flickr',       nav: true, title:'Flickr' },
      { route: 'redirect', moduleId: './redirect', name: 'redirect'}, 
      { route: 'child-router',  moduleId: './child-router', nav: true, title:'Child Router' }
    ]);

然后使用带有参数的方法导航到路由。

router.navigateToRoute('redirect', { s:'mystate'}, {replace: true});

如果要更改queryParams并使用它重新加载页面(例如,在分页链接单击时更改页码) - 您必须将determineActivationStrategyreplace一起使用。

创建视图模型并添加determineActivationStrategy函数:

import {activationStrategy} from 'aurelia-router';
export class ModelView{
  determineActivationStrategy() {
    return activationStrategy.replace;
  }
}

将激活事件添加到模型中以保存参数:

activate(params, routeConfig, navigationInstruction){
    this.queryParams = params ? params : {};
}

添加代码以使用相同的或新参数重新加载或导航:

moveToNewPage(newPageNumber){
  this.queryParams.page = newPageNumber; // change page param to new value
  this.router.navigateToRoute(this.router.currentInstruction.config.name, this.queryParams);
}

附言this.router访问使用注入,不要忘记在应用程序配置中设置路由器name

import {Router} from 'aurelia-router';
export class ModelView{
  static inject() { return [Router] };
  constructor(router){
    this.router = router;
  }
}

根据最新配置,如果未设置推送状态,则不会检索查询字符串。

将推送状态设置为 true。 并在索引中添加基本标记.html。

<base href="http://localhost:9000/"> - 索引.html

config.options.pushState = true; - app.js -> 配置路由器方法。