如何在奥里利亚的路线之间维持视图模型中的状态?

时间:2016-12-05 18:37:17

标签: aurelia

我有一个菜单和搜索模块。当我在菜单和搜索之间导航时,我想保留我的搜索结果和Search.js状态。我希望通过路由器加载模块,就像桌面应用程序一样,在模块“窗口”之间维护状态。

App.html

<template>    
    <router-view></router-view>
</template>

Search.js

import {inject} from "aurelia-framework";
import {PortalData} from "./portalData";
import $ from 'jquery';

@inject(PortalData)
export class Search
{
 constructor(portalData){
    this.portalData = portalData;  
    this.criteria = "";
    this.SearchResults = [];
}

 DoSearch(startRow){    
       this.portalData.searchSevadars(criteria)
        .then(res=> this.SearchResults = res;         
    }
}

Menu.js

import {inject} from "aurelia-framework";
import {PortalData} from "./portalData";

@inject(PortalData)
export class Start {

    constructor(portalData){
        this.portalData = portalData;
    }

      activate(){
        return this.portalData.getApplications()
            .then(apps => this.applications = apps);
    }  

2 个答案:

答案 0 :(得分:2)

最明显的解决方案是将状态存储在另一个模块中。 在两个视图中导入一些类,然后在搜索中将其存储在该类的属性中。 默认情况下,aurelia使用singleton作为注入类,因此您的视图之间将有一个共享实例。

somestate.js

export class SomeState {

   constructor(){
      this.data = undefined;
   }

}

在两者中导入此模块。 使用data属性在模块之间共享数据;

答案 1 :(得分:1)

在根应用程序文件夹/src中创建名为 core.js (或您选择的其他内容)的文件,其内容如下所示。我在这里添加了一些额外的东西以使其更加真实,但您可以简化它以满足您的特定需求。我的观点是,这个单数类可以用于很多不同的东西 - 搜索文本只是其中之一。

<强> /src/core.js

// Some example imports to support the common class
import { inject, noView } from 'aurelia-framework';
import { HttpClient, json } from 'aurelia-fetch-client';
import { I18N } from 'aurelia-i18n';
import { EventAggregator } from 'aurelia-event-aggregator';

@noView // this decorator is needed since there is no core.html
@inject(EventAggregator, I18N, HttpClient)
export class Core {
  value1 = "Test data 1";
  value2 = "Test data 2";
  constructor(eventAggregator, i18n, httpClient) {
    // store local handles
    this.eventAggregator = eventAggregator;
    this.i18n = i18n;
    this.httpClient = httpClient;

    // search info
    this.SearchResults = [];
  }

  myCustomFunction() {
    // some code here, available to any component that has core.js injected
  }
}

然后,将core.js导入并注入其他每个组件,如下所示:

<强> search.js

import {inject} from "aurelia-framework";
import {PortalData} from "./portalData";
import {Core} from "core";
import $ from 'jquery';

@inject(PortalData, Core)
export class Search
{
 constructor(portalData, core){
    this.portalData = portalData;
    this.core = core;
    this.criteria = "";
}

 DoSearch(startRow){    
       this.portalData.searchSevadars(criteria)
        .then(res=> this.core.SearchResults = res;         
    }
}