避免重定向后重新加载页面

Avoiding page reload after redirect

本文关键字:加载 新加载 重定向      更新时间:2023-09-26

Using Polymer 0.4.2 & app-router.

这是我的路由表

 <app-router>
    <app-route path="/" import="landing/landing-page.html"></app-route>
    <app-route path="/balance" import="balance/balance-view.html"></app-route>
    <app-route path="/balance/:year/:month" import="balance/balance-view.html"></app-route>
    <app-route path="/balance/:year/:month/:day" import="balance/day-view/day-view.html"></app-route>
    <app-route path="*" import="landing/landing-page.html"></app-route>
</app-router>

调用/balance时,我需要确定当前的年份和月份,并重定向到/balance/year/month。我已经尝试了router.go()window.location来执行此重定向。

如果我这样做,balance-view组件将在第一个实例下方第二次包含在内,从而导致布局中断。我目前看到解决这个问题的唯一方法是window.location.reload().但是,这会导致应用程序流中出现令人讨厌的延迟。

问题出在哪里以及如何解决?

经过一番挣扎,我让它工作了:

相同的app-router会议:

 <app-router>
  <app-route path="/" import="landing/landing-page.html"></app-route>
  <app-route path="/balance" import="balance/balance-view.html"></app-route>
  <app-route path="/balance/:year/:month" import="balance/balance-view.html"></app-route>
  <app-route path="/balance/:year/:month/:day" import="balance/day-view/day-view.html"></app-route>
  <app-route path="*" import="landing/landing-page.html"></app-route>
</app-router>

然后,在balance/balance-view.html

<polymer-element name="balance-view" attributes="year month">
  <template>
    <h1>Balance view</h1>
    <h2>Year: {{year}}</h2>
    <h2>Month: {{month}}</h2>
  </template>
  <script>   
    Polymer("balance-view", {
      domReady: function() {
        console.log(this.pathArg1);
        if (this.year === undefined) {
          var d = new Date();
          var month = new Array();
          month[0] = "January"; month[1] = "February"; month[2] = "March"; month[3] = "April";
          month[4] = "May"; month[5] = "June"; month[6] = "July"; month[7] = "August";
          month[8] = "September"; month[9] = "October"; month[10] = "November"; month[11] = "December";
          var currentYear =  d.getFullYear();
          var currentMonth = month[d.getMonth()];
          document.querySelector('app-router').go('/balance/'+currentYear+'/'+currentMonth);
        }
      }
    });
  </script>
</polymer-element>

domReady功能中,如果我检测到没有通过year,我会计算当前的年份和月份,我这样做:

document.querySelector('app-router').go('/balance/'+currentYear+'/'+currentMonth);

你可以看到它在这个 Plunker 中运行,代码在这里。

希望对您有所帮助!