【问题标题】:Traversing from this.el to parentEl returns undefined, but the reverse returns the element从this.el遍历到parentEl返回undefined,反之则返回元素
【发布时间】:2018-07-06 13:15:13
【问题描述】:

我正在尝试建立从子元素到其父元素中的组件的引用。我希望能够通过在 init() 函数中调用 this.el.parentEl.components['parent'] 来引用它,但这会返回 undefined。

其他测试用例工作正常: 1. 从父组件引用子组件在父组件中工作正常。 2.从html下面的代码sn-p引用父组件。 3. html下面的代码sn-p从子元素引用父组件。

这是生命周期的问题吗?在这种情况下,为什么孩子和父母之间存在差异?

<script src="https://aframe.io/aframe/dist/aframe-master.min.js"></script>

<script>

  AFRAME.registerComponent('parent', {

    multiple: false,

    init: function () {
      this.child = this.el.children[0].components['child']
      console.log("child component: ", this.child); //This works
    }        
  })


  AFRAME.registerComponent('child', {

    multiple: false,

    init: function () {
      this.parent = this.el.parentEl.components['parent']
      console.log("parent component: ", this.parent); //Undefined
    }        
  })

</script>

<a-scene>

  <a-entity parent>
    <a-entity child></a-entity>
  </a-entity>

</a-scene>


<script>

  var parent = document.querySelector('[parent]').components.parent
  console.log("parent component from below: ", parent); //This works

  var parentfromchild = document.querySelector('[child]').parentEl.components['parent']
  console.log("parent from child from below: ", parentfromchild); //This works

</script>

【问题讨论】:

  • 我推荐使用 Glitch 提供一个可执行的例子来说明问题

标签: aframe


【解决方案1】:

init 被调用时,父级尚未初始化。场景从孩子加载到父母。通过监听loaded 事件等待场景加载:How to detect when a scene is loaded in A-Frame?

【讨论】:

    猜你喜欢
    • 2018-07-27
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多