【问题标题】:Polymer: Uncaught TypeError: Cannot read property 'persistent' of undefined聚合物:未捕获的类型错误:无法读取未定义的属性“持久”
【发布时间】:2018-03-31 09:16:25
【问题描述】:

当我尝试在登录页面中隐藏抽屉时,它会发生错误。我使用dom-if 隐藏菜单栏,根据它的syntax 我使用<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() 存在,它返回 truefalse

【问题讨论】:

  • 上述错误表示您的抽屉尚未渲染或 dom-if 条件不正确。所以,this.$.dawer 已经没有定义了。
  • 但是登录后抽屉就来了。

标签: javascript polymer polymer-2.x drawer


【解决方案1】:

正如您在文档 here 中看到的那样,“节点使用数据绑定动态创建(包括 dom-repeat 和 dom-if 中的节点)模板)不会添加到 this.$ 哈希"

因此,由于该元素位于 dom-if 中,因此您将无法使用此“快捷方式”来获取对它的引用。因此,您必须坚持使用“旧”getElementById,同时请记住您不是在查询文档,而是在查询本地 shadow 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();
  }
});

由于没有提供第二个参数,即超时时间,因此您基本上是在说“尽快执行此操作,但不是现在”。

【讨论】:

  • 感谢您的回复先生。我像你建议的那样尝试了 this.shadowRoot.getElementById('drawer'); 并打印抽屉,但我仍然得到 null 。然后我也检查document.querySelector('#drawer')Polymer.dom(this).querySelector('#drawer')。在所有情况下,我都得到了null 的价值,简而言之,我无论如何都没有得到抽屉。知道如何解决这个问题吗?
  • 谢谢您,先生……您总是很笨。 @mishu
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2015-01-06
  • 2017-07-26
  • 2019-02-26
  • 2021-12-25
相关资源
最近更新 更多