1. Does native have components?
Vue and React are all the rage now. Front-end componentization has become a trend, but how many people know about native components. Here are a few code examples to give you a quick look at how components are written natively.
2. Implement components by inheriting HTML
Code Demo example
// Implement componentization by inheriting HTMLImageElement
class MyImg extends HTMLImageElement {
constructor() {
super(a)const src = 'https://resource.ttplus.cn/publish/app/pics/2019/04/18/233772/76d96560-7211-483d-988c-dc00d8391f41.jpg'
setTimeout(() = > {
// This points to the inherited new component
this.src = src
}, 1000)}}// The tag that the class inherits from the component name
customElements.define('my-img', MyImg, {
extends: 'img',})Copy the code
To do this, just use is=” your component name “in your inherited tag
<img is="my-img" />
Copy the code
3. Independent components
Code Demo example
demo2.html
<style>
/* Style isolation, cannot manipulate styles within MyCom */
.my_com_main {
background: pink;
}
</style>
<my-com class="my_com" cusAttr="I'm a custom property">
<span slot="middle">I'm the main thing</span>
<h2 slot="bottom">I was at the bottom of the</h2>
<div slot="head">I'm a head slot</div>
</my-com>
<script type="module" src="./demo2.js"></script>
Copy the code
MyCom.js
const template = document.createElement('template')
template.innerHTML = `
`
class MyCom extends HTMLElement {
constructor() {
super(a)// Get the attributes of the custom component
console.log(this.getAttribute('class'))
console.log(this.getAttribute('cusAttr'))
// Use attachShadow to isolate external styles
const sd = this.attachShadow({ mode: 'open' })
sd.appendChild(template.content)
}
}
customElements.define('my-com', MyCom)
Copy the code
demo2.js
import './MyCom.js'
const myComEl = document.querySelector('.my_com')
// When attachShadow is set to open, the contents of shadowRoot can be obtained and manipulated.
// If mode is closed, the node information cannot be obtained
console.log(myComEl.shadowRoot)
constmyColElChildren = myComEl.shadowRoot.children ! [...myColElChildren].forEach(el= > (el.style = 'font-size: 40px; '))
Copy the code
4. How to implement custom events
Code Demo example
Add custom events through EventTarget. The CustomEvent event is triggered by dispatchEvent.
<button id="btn_a">User-defined event A</button>
<button id="btn_b">Custom event B</button>
<script type="module">
// Create an event
const obj = new EventTarget()
// Add events
obj.addEventListener('a'.() = > alert('Triggers event A'))
obj.addEventListener('b'.() = > alert('Triggers event B'))
document.querySelector('#btn_a').onclick = () = > {
obj.dispatchEvent(new CustomEvent('a'))}document.querySelector('#btn_b').onclick = () = > {
obj.dispatchEvent(new CustomEvent('b'))}</script>
Copy the code
5. Implement a simple Dialog component
Because of too much code, directly put the link
Code Demo example
6, warehouse source address
Github.com/Layouwen/we…