Aurelia starting with params passed by PHP

2019-04-13 02:10发布

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条回答
Evening l夕情丶
2楼-- · 2019-04-13 02:46

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.

查看更多
登录 后发表回答