这里相对于 Polymer 来说是新手,但对 JS 来说并不陌生。想了解为什么以下代码片段不起作用。简而言之,我将有一个用户对象,该对象将在页面加载后填充。该对象的一个属性是roles
,它只是一个字符串数组。
dom-if
条件正在调用hasRole('user')
,该函数将返回true,但是......我觉得我只是错过了一些这里的基本概念已经让我头疼了一两天了。
我想明确一点,hasRole 函数会在页面加载时调用,但不会在页面加载之后调用。虽然我确实意识到我可以将 user.isAdmin
设为 bool,但我需要为每个可能的 Angular 色创建属性,并且希望身份验证系统比这更灵活。
目前,隐藏的“仅限管理员”部分永远不会出现。
抱歉,如果这是一个简单或愚蠢的问题或其他什么,它只是我还没有完全理解,甚至可能不知道谷歌的正确术语。
我正在使用 Polymer 2.0.0-rc.3
<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/polymer/lib/elements/dom-if.html">
<dom-module id="test1-app">
<template>
<style>
:host {
display: block;
}
</style>
<button on-click="toggle">Toggle</button>
This is visible...
<template is="dom-if" if="{{hasRole('admin')}}">
but this is hidden.
</template>
</template>
<script>
/** @polymerElement */
class Test1App extends Polymer.Element {
static get is() { return 'test1-app'; }
static get properties() {
return {
user: {
type: Object
}
};
}
toggle() {
if(this.user) {
this.user = null;
}
else {
this.user = {
name: 'Carl',
roles: ['admin','user']
}
}
}
static get observers() {
return [
'userChanged(user.*)'
]
}
hasRole(role) {
if(this.user && this.user.roles && this.user.roles.indexOf(role)>=0) {
return true;
}
else {
return false;
}
}
userChanged() {
//just observing for the sake of observing
console.log(this.user);
}
}
window.customElements.define(Test1App.is, Test1App);
</script>
</dom-module>
最佳答案
您的代码看起来不错,但 hasRole 函数仅调用一次(在第一次渲染时)。
尝试使用属性而不是函数...这样 dom-if 将根据该属性值进行渲染。
这应该有效:
<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/polymer/lib/elements/dom-if.html">
<dom-module id="test1-app">
<template>
<style>
:host {
display: block;
}
</style>
<button on-click="toggle">Toggle</button>
This is visible...
<template is="dom-if" if="{{domif}}">
but this is hidden.
</template>
</template>
<script>
/** @polymerElement */
class Test1App extends Polymer.Element {
static get is() { return 'test1-app'; }
static get properties() {
return {
user: {
type: Object
},
domif: {type: Boolean,
value: true}
};
}
toggle() {
this.domif = !this.domif;
if(this.user) {
this.user = null;
}
else {
this.user = {
name: 'Carl',
roles: ['admin','user']
}
}
}
static get observers() {
return [
'userChanged(user.*)'
]
}
hasRole(role) {
console.log('calling hasRole')
if(this.user && this.user.roles && this.user.roles.indexOf(role)>=0) {
this.domif = true;
return true;
}
else {
this.domif = false;
return false;
}
}
userChanged() {
//just observing for the sake of observing
console.log(this.user);
}
}
window.customElements.define(Test1App.is, Test1App);
</script>
</dom-module>
关于javascript - Polymer 2.0 dom-if 基于函数输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43784401/