自定義元素可以異步初始化,例如在延遲加載其定義類之后。讓我們看看這個例子,我們在 DOM 中有一個尚未初始化的元素:<component-with-async-init></component-with-async-init>在初始化之前,我們設(shè)置了value這個元素的一個屬性:querySelector('component-with-async-init').value = "GETTERS SETTERS ARE KILLED"然后我們通過將它定義為自定義元素來初始化這個元素。正如你所看到的,它的定義類有value屬性的getter 和 setter 。class ComponentWithAsyncInit extends HTMLElement{ static get is() { return 'component-with-async-init' } get value(){ console.log("Getting value") return "VALUE FROM GETTER" } set value(v){ console.log("Setting value") }}window.customElements.define(ComponentWithAsyncInit.is, ComponentWithAsyncInit);Getter 和 setter(或任何方法)現(xiàn)在被殺死,如您所見:querySelector('component-with-async-init').value //"GETTERS SETTERS ARE KILLED"我在最新的 Safari、Firefox 和 Chrome 中觀察到了這種行為,其他未經(jīng)測試。此問題會影響 Polymer 和 Lit-Element 庫以及純自定義元素。似乎它在每個瀏覽器中的工作方式都相同。問題:這真的是預(yù)期的行為嗎?如果在元素定義之前設(shè)置了屬性,則 Getter 和 Setter 以及任何方法都會被清除。如果是,那么解決方法是什么,因為我們通常無法控制何時設(shè)置元素值片段:document.querySelector('component-with-async-init').value = "SETTERS GETTERS KILLED"document.querySelector('component-with-async-init').getSomeValue = "GET SOME VALUE KILLED"class ComponentWithAsyncInit extends HTMLElement{ static get is() { return 'component-with-async-init' } get value(){ console.log("Getting value") return "VALUE FROM GETTER" } set value(v){ console.log("Setting value") } getSomeValue(){ return "SOME VALUE" }}window.customElements.define(ComponentWithAsyncInit.is, ComponentWithAsyncInit);console.log("getSomeValue method:")console.log(document.querySelector('component-with-async-init').getSomeValue) console.log("Reading value:")console.log(document.querySelector('component-with-async-init').value)<component-with-async-init></component-with-async-init>
如果在定義元素之前設(shè)置了相同名稱的屬性,則 CustomElement 的初始化會刪除類方法
炎炎設(shè)計
2021-10-07 10:48:16