Web Components native browser APIs को एक सेट हुन् जसले reusable, encapsulated custom HTML elements बनाउन सक्षम गराउछ — framework-agnostic र standards-based। तीन प्रविधि एकै साथ काम गर्छन्:
Web Components native browser APIs को एक सेट हुन् जसले reusable, encapsulated custom HTML elements बनाउन सक्षम गराउछ — framework-agnostic र standards-based। तीन प्रविधि एकै साथ काम गर्छन्:
<template>, <slot>) — निष्क्रिय, reusable markup।class UserCard extends HTMLElement {
connectedCallback() { // lifecycle: runs when added to the page
const shadow = this.attachShadow({ mode: "open" }); // create shadow DOM
shadow.innerHTML = `
<style> h2 { color: blue; } </style>
<h2>${this.getAttribute("name")}</h2>
<slot></slot>
`;
}
}
customElements.define("user-card", UserCard); // name MUST contain a hyphen
<user-card name="Ann">Extra content goes in the slot</user-card>
Shadow root भित्र को styles scoped हुन्छन् — पृष्ठको CSS भित्र पुग्न सक्दैन, र component को CSS बाहिर छिर्दैन। यो global-CSS समस्या को native समाधान गर्छ:
/* page CSS */ h2 { color: red; } /* does NOT affect the <h2> inside user-card */
connectedCallback() // added to DOM
disconnectedCallback() // removed from DOM (cleanup)
attributeChangedCallback(name, old, val) // an observed attribute changed
static get observedAttributes() { return ["name"]; }
Web Components ले तपाईंलाई reusable widgets बनाउन दिन्छ जो कुनै पनि framework मा (वा कुनै पनि छैन) real style/DOM encapsulation सँग काम गर्छन् — design systems र micro-frontends को लागि आदर्श विभिन्न stacks प्रयोग गर्ने टिमहरू जस्तै साझेदारी।
यो तरिका पनि Shoelace जस्ता libraries framework-agnostic components जहाज गर्छन्।
Trade-offs (verbose API, SSR/styling complexity) को मतलब app developers अक्सर React/Vue को पसन्द गर्छन्, तर platform primitive शक्तिशाली र standards-based छ।
विस्तृत उत्तरसहित IT अन्तर्वार्ता प्रश्नहरूको पुस्तकालय — जुनियरदेखि सिनियरसम्म।
दान गर्नुहोस्