[英]Polymer: Uncaught TypeError: Cannot read property 'persistent' of undefined
當我嘗試在“登錄”頁面中隱藏抽屜時,發生錯誤。 我使用dom-if
隱藏菜單欄,根據它的語法,我使用了<template>
標簽。 但是會發生錯誤。
聚合物代碼
<!-- Drawer content -->
<template is="dom-if" if="[[_isLogin()]]">
<app-drawer id="drawer" slot="drawer" swipe-open="[[narrow]]">
<app-toolbar>Menu</app-toolbar>
<iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
<a name="homepage" href="[[rootPath]]homepage">Homepage</a>
<a name="profile" href="[[rootPath]]profile">Profile</a>
<a name="temp" href="[[rootPath]]temp">Temp</a>
</iron-selector>
</app-drawer>
</template>
腳本
_routePageChanged(page) {
if(this._isLogin()) {
// If no page was found in the route data, page will be an empty string.
// Default to 'homepage' in that case.
this.page = page || 'homepage';
// Close a non-persistent drawer when the page & route are changed.
if (!this.$.drawer.persistent) {
this.$.drawer.close();
}
} else {
this.page = 'login';
}
}
注意: _isLogin()
在那里,它返回true
或false
如您在此處的文檔中所見,“ 使用數據綁定動態創建的節點(包括dom-repeat和dom-if模板中的節點)未添加到this。$哈希 ”
因此,由於該元素位於dom-if內部,因此您將無法使用此“快捷方式”來獲取對該元素的引用。 因此,您必須堅持使用“舊的” getElementById ,同時要記住您不是在查詢文檔,而是查詢本地陰影dom。 所以這:
if (!this.$.drawer.persistent) {
this.$.drawer.close();
}
可能變成:
var drawer = this.shadowRoot.getElementById('drawer');
if (drawer.persistent) {
drawer.close();
}
更新 :由於您說它仍然不起作用,我想我應該提到您需要考慮的另一件事。 在您的代碼中,顯示該元素的條件和要查詢的條件都是相同的,由_isLogin
方法返回。
老實說,我不知道我要建議的是原因還是建議的解決方案,但是我認為您應該給它一些時間,將元素實際標記到頁面中以便能夠查詢(工作)圍繞單個執行線程之類的東西)。 因此,作為解決方法,您可以將代碼包裝在setTimeout回調中,如下所示:
setTimeout(() => {
var drawer = this.shadowRoot.getElementById('drawer');
if (drawer.persistent) {
drawer.close();
}
});
由於未提供第二個參數timeout,因此您基本上是說“ 盡快執行此操作,但現在不執行 ”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.