检查角色时无限循环。 VueJS
Infinite loop when checking roles. VueJS
有一个导航栏,其中根据用户的角色显示元素:
<b-navbar-toggle
right
class="jh-navbar-toggler d-lg-none"
href="javascript:void(0);"
data-toggle="collapse"
target="header-tabs"
aria-expanded="false"
aria-label="Toggle navigation">
<font-awesome-icon icon="bars"/>
</b-navbar-toggle>
<b-collapse is-nav id="header-tabs">
<b-navbar-nav class="ml-auto">
<b-nav-item-dropdown
right
id="pass-menu"
v-if="hasAnyAuthority('ROLE_USER') && authenticated"
:class="{'router-link-active': subIsActive('/pass')}"
active-class="active"
class="pointer">
<span slot="button-content" class="navbar-dropdown-menu">
<font-awesome-icon icon="ticket-alt"/>
<span>First element</span>
</span>
</b-nav-item-dropdown>
<b-nav-item-dropdown
right
id="dictionaries-menu"
v-if="hasAnyAuthority('ROLE_ADMIN') && authenticated"
:class="{'router-link-active': subIsActive('/dictionary')}"
active-class="active"
class="pointer">
<span slot="button-content" class="navbar-dropdown-menu">
<font-awesome-icon icon="book"/>
<span>Second element</span>
</span>
</b-nav-item-dropdown>
</b-navbar-nav>
如果我为两个元素设置相同的角色,例如 ROLE_USER
,一切正常。但是当两个元素的角色不同时,一个无限循环开始,一切都冻结了。
用于检查角色的组件:
@Component
export default class JhiNavbar extends Vue {
@Inject('loginService')
private loginService: () => LoginService;
@Inject('accountService') private accountService: () => AccountService;
public version = VERSION ? 'v' + VERSION : '';
private currentLanguage = this.$store.getters.currentLanguage;
private languages: any = this.$store.getters.languages;
private hasAnyAuthorityValue = false;
created() {}
public get authenticated(): boolean {
return this.$store.getters.authenticated;
}
public hasAnyAuthority(authorities: any): boolean {
this.accountService()
.hasAnyAuthorityAndCheckAuth(authorities)
.then(value => {
this.hasAnyAuthorityValue = value;
});
return this.hasAnyAuthorityValue;
}
}
使用用户帐户的服务:
export default class AccountService {
constructor(private store: Store<any>, private router: VueRouter) {
this.init();
}
public init(): void {
this.retrieveProfiles();
}
public retrieveProfiles(): void {
axios.get('management/info').then(res => {
if (res.data && res.data.activeProfiles) {
this.store.commit('setRibbonOnProfiles', res.data['display-ribbon-on-profiles']);
this.store.commit('setActiveProfiles', res.data['activeProfiles']);
}
});
}
public retrieveAccount(): Promise<boolean> {
return new Promise(resolve => {
axios
.get('api/account')
.then(response => {
this.store.commit('authenticate');
const account = response.data;
if (account) {
this.store.commit('authenticated', account);
if (sessionStorage.getItem('requested-url')) {
this.router.replace(sessionStorage.getItem('requested-url'));
sessionStorage.removeItem('requested-url');
}
} else {
this.store.commit('logout');
this.router.push('/');
sessionStorage.removeItem('requested-url');
}
resolve(true);
})
.catch(() => {
this.store.commit('logout');
resolve(false);
});
});
}
public hasAnyAuthorityAndCheckAuth(authorities: any): Promise<boolean> {
if (typeof authorities === 'string') {
authorities = [authorities];
}
if (!this.authenticated || !this.userAuthorities) {
const token = localStorage.getItem('jhi-authenticationToken') || sessionStorage.getItem('jhi-authenticationToken');
if (!this.store.getters.account && !this.store.getters.logon && token) {
return this.retrieveAccount();
} else {
return new Promise(resolve => {
resolve(false);
});
}
}
for (let i = 0; i < authorities.length; i++) {
if (this.userAuthorities.includes(authorities[i])) {
return new Promise(resolve => {
resolve(true);
});
}
}
return new Promise(resolve => {
resolve(false);
});
}
public get authenticated(): boolean {
return this.store.getters.authenticated;
}
public get userAuthorities(): any {
return this.store.getters.account.authorities;
}
}
@bigless 有解决方案:
...
private hasAdminAuthorityValue = false;
private hasUserAuthorityValue = false;
...
public hasAdminAuthority(): boolean {
this.accountService()
.hasAnyAuthorityAndCheckAuth('ROLE_ADMIN')
.then(value => {
this.hasAdminAuthorityValue = value;
});
return this.hasAdminAuthorityValue;
}
public hasUserAuthority(): boolean {
this.accountService()
.hasAnyAuthorityAndCheckAuth('ROLE_USER')
.then(value => {
this.hasUserAuthorityValue = value;
});
return this.hasUserAuthorityValue;
}
这是由 Vue 的反应性引起的。您在 v-if
语句中使用异步方法,这主要是个坏主意。 Vue 监视此方法的所有反应依赖项,如果任何依赖项发生变化,它会再次重新评估此语句(这意味着再次调用该函数)。这是故事的一部分。
现在为什么只有当角色不同时才会发生这种情况。因为你使用了 shared 属性 hasAnyAuthorityValue
这是上面提到的方法的反应依赖。
例如:它立即获得 ROLE_USER、returns hasAnyAuthorityValue
的权限(同步),但稍后会在 promise(异步)中获取和更新此值。如果异步结果没有改变(一个角色),它可以工作,但是当 hasAnyAuthorityValue
的值在 ROLE_USER 和 ROLE_ADMIN 异步结果之间切换时,它会陷入无限循环。
有很多解决方案。 f.e。在创建阶段将 hasAnyAuthority(any)
的结果保存为数据的 属性 值,或者为每个角色使用不同的 属性 名称而不是共享名称。
有一个导航栏,其中根据用户的角色显示元素:
<b-navbar-toggle
right
class="jh-navbar-toggler d-lg-none"
href="javascript:void(0);"
data-toggle="collapse"
target="header-tabs"
aria-expanded="false"
aria-label="Toggle navigation">
<font-awesome-icon icon="bars"/>
</b-navbar-toggle>
<b-collapse is-nav id="header-tabs">
<b-navbar-nav class="ml-auto">
<b-nav-item-dropdown
right
id="pass-menu"
v-if="hasAnyAuthority('ROLE_USER') && authenticated"
:class="{'router-link-active': subIsActive('/pass')}"
active-class="active"
class="pointer">
<span slot="button-content" class="navbar-dropdown-menu">
<font-awesome-icon icon="ticket-alt"/>
<span>First element</span>
</span>
</b-nav-item-dropdown>
<b-nav-item-dropdown
right
id="dictionaries-menu"
v-if="hasAnyAuthority('ROLE_ADMIN') && authenticated"
:class="{'router-link-active': subIsActive('/dictionary')}"
active-class="active"
class="pointer">
<span slot="button-content" class="navbar-dropdown-menu">
<font-awesome-icon icon="book"/>
<span>Second element</span>
</span>
</b-nav-item-dropdown>
</b-navbar-nav>
如果我为两个元素设置相同的角色,例如 ROLE_USER
,一切正常。但是当两个元素的角色不同时,一个无限循环开始,一切都冻结了。
用于检查角色的组件:
@Component
export default class JhiNavbar extends Vue {
@Inject('loginService')
private loginService: () => LoginService;
@Inject('accountService') private accountService: () => AccountService;
public version = VERSION ? 'v' + VERSION : '';
private currentLanguage = this.$store.getters.currentLanguage;
private languages: any = this.$store.getters.languages;
private hasAnyAuthorityValue = false;
created() {}
public get authenticated(): boolean {
return this.$store.getters.authenticated;
}
public hasAnyAuthority(authorities: any): boolean {
this.accountService()
.hasAnyAuthorityAndCheckAuth(authorities)
.then(value => {
this.hasAnyAuthorityValue = value;
});
return this.hasAnyAuthorityValue;
}
}
使用用户帐户的服务:
export default class AccountService {
constructor(private store: Store<any>, private router: VueRouter) {
this.init();
}
public init(): void {
this.retrieveProfiles();
}
public retrieveProfiles(): void {
axios.get('management/info').then(res => {
if (res.data && res.data.activeProfiles) {
this.store.commit('setRibbonOnProfiles', res.data['display-ribbon-on-profiles']);
this.store.commit('setActiveProfiles', res.data['activeProfiles']);
}
});
}
public retrieveAccount(): Promise<boolean> {
return new Promise(resolve => {
axios
.get('api/account')
.then(response => {
this.store.commit('authenticate');
const account = response.data;
if (account) {
this.store.commit('authenticated', account);
if (sessionStorage.getItem('requested-url')) {
this.router.replace(sessionStorage.getItem('requested-url'));
sessionStorage.removeItem('requested-url');
}
} else {
this.store.commit('logout');
this.router.push('/');
sessionStorage.removeItem('requested-url');
}
resolve(true);
})
.catch(() => {
this.store.commit('logout');
resolve(false);
});
});
}
public hasAnyAuthorityAndCheckAuth(authorities: any): Promise<boolean> {
if (typeof authorities === 'string') {
authorities = [authorities];
}
if (!this.authenticated || !this.userAuthorities) {
const token = localStorage.getItem('jhi-authenticationToken') || sessionStorage.getItem('jhi-authenticationToken');
if (!this.store.getters.account && !this.store.getters.logon && token) {
return this.retrieveAccount();
} else {
return new Promise(resolve => {
resolve(false);
});
}
}
for (let i = 0; i < authorities.length; i++) {
if (this.userAuthorities.includes(authorities[i])) {
return new Promise(resolve => {
resolve(true);
});
}
}
return new Promise(resolve => {
resolve(false);
});
}
public get authenticated(): boolean {
return this.store.getters.authenticated;
}
public get userAuthorities(): any {
return this.store.getters.account.authorities;
}
}
@bigless 有解决方案:
...
private hasAdminAuthorityValue = false;
private hasUserAuthorityValue = false;
...
public hasAdminAuthority(): boolean {
this.accountService()
.hasAnyAuthorityAndCheckAuth('ROLE_ADMIN')
.then(value => {
this.hasAdminAuthorityValue = value;
});
return this.hasAdminAuthorityValue;
}
public hasUserAuthority(): boolean {
this.accountService()
.hasAnyAuthorityAndCheckAuth('ROLE_USER')
.then(value => {
this.hasUserAuthorityValue = value;
});
return this.hasUserAuthorityValue;
}
这是由 Vue 的反应性引起的。您在 v-if
语句中使用异步方法,这主要是个坏主意。 Vue 监视此方法的所有反应依赖项,如果任何依赖项发生变化,它会再次重新评估此语句(这意味着再次调用该函数)。这是故事的一部分。
现在为什么只有当角色不同时才会发生这种情况。因为你使用了 shared 属性 hasAnyAuthorityValue
这是上面提到的方法的反应依赖。
例如:它立即获得 ROLE_USER、returns hasAnyAuthorityValue
的权限(同步),但稍后会在 promise(异步)中获取和更新此值。如果异步结果没有改变(一个角色),它可以工作,但是当 hasAnyAuthorityValue
的值在 ROLE_USER 和 ROLE_ADMIN 异步结果之间切换时,它会陷入无限循环。
有很多解决方案。 f.e。在创建阶段将 hasAnyAuthority(any)
的结果保存为数据的 属性 值,或者为每个角色使用不同的 属性 名称而不是共享名称。