Hướng dẫn create component in javascript
Yesterday, we looked at what web components are. Today, I wanted to share how to actually create one. Show Let’s dig in! Today’s article is an excerpt from my new course and ebook on web components with vanilla JS. Creating a web componentTo help make the concepts in this guide tangible, we’re going to build a really simple web component:
When we’re done, the component will load a We’ll also include some custom styling, and add some hooks that developers can use to customize it a bit (without breaking things). Registering a web componentTo create a web component, the first thing you have to do is register it with JavaScript. To do that, we’ll
first use a JavaScript class to extend the Let’s call this one
After we create our new class, we need to define our component using the The first argument is the The second argument is the (As a best practice, we should make sure that
Now, we’ve registered a new web component. It doesn’t do anything yet, but it exists! The web component lifecycleAs the browser parses and renders your web component into the DOM, there are a few lifecycle callback functions that run at various times.
We can include functions that run on each of these events inside our web component class. Because we’re extending an existing class, the
If you include a web component in the UI and do nothing else on the page, the
If you were to move your element using something like the If you removed it with the
Generating the web component HTMLNow that we have a registered web component, we need to generate some actual HTML in the UI. Inside the In our case, let’s add a
Now, when the web component is loaded, this is what’s displayed in the DOM.
Now we’ve got a basic web component in place and rendering HTML into the UI. Here’s a demo. Tomorrow, we’ll look at how to add interactivity. |