Polymer 2.0 无法从 id 获取 child

Polymer 2.0 not able to get child from id

我是 Polymer 的新手,最近遇到了一个问题。我动态创建了我的 web-component 的一定数量的实例,我希望能够从我的 parent-component 中调用这些实例的方法,但我不知道该怎么做它甚至包含我在网上找到的答案。

这是我的 parent 方法,我在其中尝试调用 children 方法(e.detail.id 匹配我的 children I'我正在尝试到达):

childObj: function(e) {
     var name = "selectObj"+e.detail.id;
     this.$.name.hello();
},

还有我的child基本方法:

hello: function() {
     console.log("hello");
}

名称获取的 ID 存在,但我仍然收到此错误

TypeError: Polymer.dom(...).querySelector(...) is null

我也尝试用 this.$$('#selectObj'+e.detail.id) 替换 this.$.name.hello() 但我仍然得到同样的错误。

以下是我创建 childrens 元素的方法:

newObj: function() {
            var dynamicSelect = document.createElement("pbd-object-select");
            dynamicSelect.num = this.nbObj;
            var newId = "selectObj" + this.nbObj;
            dynamicSelect.id = newId;  
            Polymer.dom(this.root).querySelector("#listeObjet").appendChild(dynamicSelect);
        },

您尝试查询该元素的方式存在两个问题。其中之一是通过这样做:

this.$.name.hello();

您基本上是在寻找 ID 为 "name" 的元素,而不是 ID 等于变量 name 中的元素的元素。类似于:

this.$[name].hello();

一般情况下可能效果更好,但在您的特定情况下仍然会出现一些问题。 this.$ 只是一个 "shortcut" 以简单的方式通过 ID 获取元素, 但是 ,它只是一个对象,其中引用了存在并具有 ID 的元素当元素连接时。因此,它不适用于有条件地包含的元素(例如在 dom-if 中)或动态生成的元素,例如您的情况。

你可以只使用 getElementById 方法,就像你在 vanilla JS 中所做的那样,只要记住你是在你的元素中而不是在 document 中查询。所以它会是这样的:

this.shadowRoot.getElementById("selectObj"+e.detail.id).hello()