简体   繁体   English

聚合物2定义全局变量

[英]Polymer 2 define global variables

I recently started working with Polymer 2.0, and so far i am in love with it. 我最近开始使用Polymer 2.0,到目前为止我爱上了它。 I am used to Angular in combination with typescript, and i loved how easy it was to define global variables. 我习惯将Angular与typescript结合使用,我喜欢定义全局变量是多么容易。

Wanted outcome: Let's say i have a variable named: "Username" in the login page. 想要的结果:假设我在登录页面中有一个名为“Username”的变量。 The var Username is currently "Guest", so in my welcome-page i have the message "Hello Guest!". var用户名当前是“访客”,所以在我的欢迎页面中,我有消息“Hello Guest!”。 The username in the login page changes from guest => not-a-guest The welcome-page now says: Hello not-a-guest!". 登录页面中的用户名从guest => not-a-guest变为欢迎页面现在显示:Hello not-a-guest!“。

Is there a way to do this without passing the variable like ? 有没有办法在不传递变量的情况下这样做? Because everytime I want to use the username property, i now have to pass the username like above. 因为每次我想使用username属性,我现在必须传递上面的用户名。 (so if i need the username in a child of a child of a child component, I now have to pass the username to all parents aswell). (因此,如果我需要子组件子项的子项中的用户名,我现在必须将用户名传递给所有父项)。 Now ofcourse this is about a user so in this case, localstorage/sessionstorage would be alright, but this is just an example. 现在,这是关于用户的,所以在这种情况下,localstorage / sessionstorage会没问题,但这只是一个例子。 I'd like to use the global defining for something else, and saving that in localstorage would not be ideal. 我想将全局定义用于其他东西,并将其保存在localstorage中并不理想。

I found a lot of Polymer 1 solutions, but i'd love to have my application in full Polymer 2.0. 我发现了很多Polymer 1解决方案,但我很乐意将我的应用程序用于完整的Polymer 2.0。

Thanks a ton! 万分感谢!

I figured and make a webcomponent myself . 我自己想了一个网络组件 usage: 用法:

// Login component
// Define global variable
<brum-global-var key="username" value="{{username}}"></global-variable>

// welcome-page 
// Use global variable
<brum-global-var key="username" value="{{username}}" readonly></global-variable>

One option would be to use a mixin class and extend it in whatever component you need it. 一种选择是使用mixin类并将其扩展到您需要的任何组件中。 Read more here . 在这里阅读更多。

有一个iron-meta元素可以用来完成你创建的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM