Method to display child elements in WebComponent
P粉514001887
2023-09-04 09:18:39
<p>I'm trying to rebuild a React component into a WebComponent in order to get rid of the dependency on React. </p>
<p>I would like to see a WebComponent like this in HTML: </p>
<pre class="brush:php;toolbar:false;"><editable-h1>Hello, world</editable-h1></pre>
<p>It should look like this:</p>
<pre class="brush:php;toolbar:false;"><span>
<h1>Hello, world</h1>
<button onClick=this.onEdit>Edit</button>
</span></pre>
<p>If I click the edit button, I want it to appear like this: </p>
<pre class="brush:php;toolbar:false;"><form>
<input type='text' value='Hello, world'></input>
<button onClick=this.onSave>Save</button>
</form></pre>
<p>Clicking the Save button will save the changes to the database via an API call and return to the original rendering (but with the text already edited). </p>
<p>I believe I can handle switching rendering and making API calls, but what I'm confused about is how to get the child element text "Hello, world" from the initial WebComponent in order to render. </p>
Trigger the connectedCallback event on
So youropen tag
<editable-h1>
Hello World
To wait until parsing is completed before executing, use’s
innerHTML has not been parsedsetTimeout
NOTE: All tools and libraries that provideparsedCallback
If you think one line ofwill use a similar trick under the hood, using
requestAnimationFrameor
MutationObserver(there are many more lines of code) .
setTimeout
And follow WC experts, this discussion continues:is a hack, or you don't want to waste that
millisecondusing
setTimeout, you can check out Andrea Giammarchi's html- parsed-element code (Of course it requires loading and parsing, and it also increases dependencies and code complexity, so it takes more time overall)Need a callback function to execute after the child element changes or parsing is completed https://github.com/WICG/webcomponents/issues/809
All methods boil down to the same goal: Wait for the event loop to be empty
What is an event loop?https://www.youtube.com/watch?v=8aGhZQkoFbQ