您似乎正在为路由寻找 inlineView("<your html here/>") 类型的功能,以便导航到目标路由将直接在 router-view 元素中呈现 HTML。
aurelia-router 无法直接实现这一点,因为没有 ViewModel,就无法调用 ActivationStrategy。 Aurelia-router 想在 something 上调用canActivate、activate、canDeactivate、deactivate。
但是,如果您只是想以编程方式定义标记,并且不想为每个单独的标记声明一个 ViewModel,那么可以使用 compose 元素结合 inlineViewStrategy 巧妙地解决这个问题.
使用这种方法,您只需要一个 View/ViewModel 对,它负责根据当前路由检索正确的 HTML,然后呈现该 HTML。
还有其他方法可以做到这一点,但 AFAIK 这种方法涉及的管道数量最少。
当然,您还需要一个对象来存储 HTML/路由对,以及一个服务来存储/检索这些对象。
您可以在此处查看实时工作版本(包括一些用于说明问题的 cmets):
https://gist.run/?id=8c7e02ce1ee0e25d966fea33b826fe10
app.js
import { inject } from "aurelia-framework";
import { Router } from "aurelia-router";
import { FaqService } from "./faq-service";
@inject(Router, FaqService)
export class App {
constructor(router, faqService) {
router.configure(config => {
config.map({ route: "", moduleId: "./empty" });
config.map({ route: "faq/:route", moduleId: "./faq-detail" });
});
this.router = router;
this.faqService = faqService;
}
openFaq(item) {
this.router.navigate(`faq/${item.route}`);
}
}
app.html
<template>
<router-view></router-view>
<ul>
<li repeat.for="item of faqService.faqItems" click.delegate="openFaq(item)">
${item.title}
</li>
</ul>
</template>
empty.js(只是为了方便默认空路由):
import { inlineView } from "aurelia-framework";
@inlineView("<template>no content</template>")
export class Empty {}
faq-service.js
import { singleton } from "aurelia-framework";
class FaqItem {
constructor(route, title, markup) {
this.route = route;
this.title = title;
this.markup = markup;
}
}
@singleton(false)
export class FaqService {
constructor() {
this.faqItems = [
new FaqItem("question-1", "Question 1", "<h4>Question 1</h4><p>Answer 1</p>"),
new FaqItem("question-2", "Question 2", "<h4>Question 2</h4><p>Answer 2</p>"),
new FaqItem("question-3", "Question 3", "<h4>Question 3</h4><p>Answer 3</p>")
];
}
getByRoute(route) {
return this.faqItems.find(i => i.route === route);
}
}
faq-detail.js
import { inject, InlineViewStrategy } from "aurelia-framework";
import { FaqService } from "./faq-service";
@inject(FaqService)
export class FaqDetail {
constructor(service) {
this.service = service;
}
activate(param) {
let item = this.service.getByRoute(param.route);
this.viewStrategy = new InlineViewStrategy(`<template>${item.markup}</template>`)
}
}
faq-detail.html
<template>
<compose view.bind="viewStrategy"></compose>
</template>