Aurelia starting with params passed by PHP

 ̄綄美尐妖づ 提交于 2019-12-21 21:24:40

问题


I need to pas params to Aurelia on start. Depending on values passed the application will have diffrent state. This application is injected on page which is build with PHP, so the best way would be starting it with parameters specified with PHP code. Is there any way to do this?


回答1:


Any data you can access in normal JS you can access with Aurelia. Maybe you could use a data-* attribute to do this? When you use a main file by doing aurelia-app="main", the framework instance you get passed to your configure method has ahostproperty that is the element the framework is being attached to. You could placedata-*attributes on this element and then access them via thedataset` property of this element (IE11+ https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset).

Your index.html or equivalent might have something like this:

  <body aurelia-app="main"  
        data-param1="value1" 
        data-param2="value2">

Your main.js can then access these values easily:

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging();

  aurelia.container.registerInstance('serverData', 
    Object.assign({}, aurelia.host.dataset))

  aurelia.start().then(() => aurelia.setRoot());  
}

Here is a runnable example: https://gist.run/?id=55eae2944b00b11357868262e095d28c

You could even put JSON in the data attribute if you use single quotes around the attribute value: https://gist.run/?id=57417139aa8c0c66b241c047efddf3dd

Edit: I've improved this answer based on the similar answer Jeremy Danyow posted. Both linked gists have been updated as well.



来源:https://stackoverflow.com/questions/40024102/aurelia-starting-with-params-passed-by-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!