如何在Aurelia中动态绑定route-href参数?

Nat*_*ase 5 parameters binding routing router aurelia

我正在使用pushState,而不是对URL结构使用哈希。

我有一条路线,它有一些参数绑定-一些可选的:

route: [                        
     'chart/:chartType/:id',
     'chart/:chartType/:id/:view?',
     'chart/:chartType/:id/page/:page?',
     'chart/:chartType/:id/:view?/page/:page?'
], 
Run Code Online (Sandbox Code Playgroud)

然后我有了我的route-href,并且在那儿有必要的绑定:

route-href="route.bind: chart; params.bind: { id: chartId, chartType: type, view: viewType, page: pageNum }"

...但是如果我不总是想要一个的所有路由参数route-href怎么办?与之类似,我希望能够仅链接到使用chartType和id的路由,而不必为此路由上的每个参数组合创建单独的路由。

我知道我可以使用“?” 在路由器配置中指定路由可选,但是如何在我的route-href链接中使参数可选?

做这样的事情会引发错误:

route-href="route.bind: chart; params.bind: { id: chartId, chartType: type, view?: viewType, page?: pageNum }"

而且我似乎无法使用这样的.bind语法(这也会出错):

route-href="route.bind: chart; params.bind: { id: chartId, chartType: type, view.bind: hasViewParam, page.bind: hasPageParam }"

这是什么神奇的语法技巧?

Mat*_*vis 6

问题在于,虽然 Aurelia 可以观察基元、对象和数组,但它无法观察对象或数组元素的属性。

<a route-href="route.bind: chart; params.bind: { id: chartId, chartType: type, view: viewType, page: pageNum }">link</a>
Run Code Online (Sandbox Code Playgroud)

chartId这可以工作,但在、typeviewTypepageNum更新时不会更新。传递给绑定的值是 { id, ChartType view, page } 对象,Aurelia 无法观察该对象的属性。因此,最好的办法就是生成一个对象。

也许在你的视图模型中你有:

export class ViewModel {
  chartId;
  type;
  viewType;
  pageNum;
}
Run Code Online (Sandbox Code Playgroud)

将其增强为:

import { observable } from 'aurelia-framework';

export class ViewModel {

  @observable({ changeHandler: 'generateLinkParams'}) chartId;
  @observable({ changeHandler: 'generateLinkParams'}) type;
  @observable({ changeHandler: 'generateLinkParams'}) viewType;
  @observable({ changeHandler: 'generateLinkParams'}) pageNum;
  linkParams;

  generateLinkParams() {
    const { chartId, type, viewType, pageNum } = this;
    this.linkParams = { chartId, type, viewType, pageNum };
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,由于 linkParams 对象的值正在更新,而不仅仅是其属性,因此 Aurelia 将观察它。Fabio 给出的解决方案如下:

<a route-href="route.bind: chart; params.bind: linkParams">link</a>
Run Code Online (Sandbox Code Playgroud)


Fab*_*Luz 4

尝试创建一个chartParams属性。每当您更改时更新此属性chart。然后,你就可以这样做了route-href="route.bind: chart; params.bind: chartParams。(我还没有测试过这种方法,但我认为它会起作用)

另一种选择是手动生成路线。例如:

this.myRoute = this.router.generate(routeName, params);
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其绑定到链接标记:

<a href.bind="myRoute">My Route</a>
Run Code Online (Sandbox Code Playgroud)