【问题标题】:Add query parameters to the route in Aurelia向 Aurelia 中的路由添加查询参数
【发布时间】:2018-01-22 02:25:04
【问题描述】:

我有一个看起来像 http://127.0.0.1:8000/api/articles/?page=2 的分页 API,我想在 Aurelia 的前端使用相同的分页。

我为nextprevious 页面创建了两个按钮:

<button
  type="button"
  click.delegate="getArticles(articles.previous)">prev</button>
<button
  type="button"
  click.delegate="getArticles(articles.next)">next</button>

当我单击next 时,会出现一个新的GET 请求,并且文章列表会更新,但我还想在 URL 上添加参数,以便用户可以看到他在第二页上。 那么,如何在路由末尾添加/?page=2

我知道如何使用与子组件不同的组件添加参数,但这次我使用的是同一个组件。

谢谢。

【问题讨论】:

    标签: aurelia


    【解决方案1】:

    Aurelia 支持开箱即用的路由中的查询参数。您不需要在路由本身中定义 page 参数。所有查询参数都只是给activate方法的params参数。

    import { inject } from 'aurelia-framework';
    import { Router, activationStrategy } from 'aurelia-router';
    
    @inject(Router)
    export class Articles(Router) {
        constructor(router) {
            this.router = router;
        }
    
        activate(params) {
            this.page = parseInt(params.page || '1');
    
            // TODO: Load your articles from the API here
            // this.articles = <fetch call using this.page>
        }
    
        // This is necessary to tell Aurelia router not to reuse 
        // the same view model whenever navigating between pages
        // so that the activate method gets called each time
        determineActivationStrategy() {
            return activationStrategy.replace;
        }
    
        // TODO: Check if we can go to previous and next page, etc.
        nextPage() {
            this.router.navigateToRoute('articles', { page: this.page + 1 });
        }
    
        previousPage() {
            this.router.navigateToRoute('articles', { page: this.page - 1 });
        }
    }
    

    【讨论】:

    • 这很有帮助。无论如何使用--this.page 而不是this.page - 1 可以防止出现错误。另外,我不需要activateStrategy,但很高兴知道,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多