This article brings you relevant knowledge about Slots. The function of Slots is to pass values to template elements and enhance the flexibility and versatility of template elements. I hope it will be helpful to everyone.
Students who are familiar with Vue should all know the concept of "slot". By using slots, the organization of page content can be made more flexible.
There is also the concept of slots in the Web Components system. Today we will take a closer look at Slots. This article mainly includes the following content:
- Why use Slots?
- Related features of Slots
The role of Slots
Let’s first look at a template element:
<template> <p>MY CARD</p> <p> My name is 编程三昧。 </p></template>
Since it is a template, it means It will be used in many places, but there will be a problem here: All places that use this template will display the content in the template, that is, not everyone's name is called "Programming Samadhi" .
In this case, people with other names cannot use this template. Obviously, this goes against the original intention of using the template. The scope of use of this template is too narrow and there is no universal sex.
To make this template universal, the key point is whether the content displayed in .details
is universal.
Use your brain to think about whether we can set the "Programming Samadhi" as dynamic content. Whoever uses this template can pass in his or her name. It just so happens that Slots (slots) can achieve this effect, as follows:
<!--在模板中使用 slot 进行占位--><template> <p>MY CARD</p> <p> My name is <slot>编程三昧</slot>。 </p></template><!--在使用上面模板的自定义元素中给 slot 传值--><my-card> <span>插槽传值</span></my-card><my-card> <span>web Components</span></my-card>
The corresponding JS code is as follows:
class MyCard extends HTMLElement { constructor () { super(); const template = document.getElementById('cardTmp'); const templateContent = template.content; this.attachShadow({mode: 'open'}).appendChild( templateContent.cloneNode(true) ); }}customElements.define('my-card', MyCard);
Achieve the effect:
Through the above example, we can summarize the role of Slots in one sentence: The role of Slots is to transfer values to template elements and enhance the flexibility and versatility of template elements.
Related features of Slots
For the relevant features of Slots, I will explain them one by one in the form of questions and answers.
What is the role of the name attribute of Slots?
Slots with a specified name are called "named slots", and name is the unique identifier of the slot.
You need to use the slot attribute with the same value as Slots.name
on the element that introduces slot content. Look at the following code:
<template> <p>MY CARD</p> <p> My name is <slot>19</slot>。 </p></template><my-card> <span>编程三昧</span></my-card><my-card> <span>web Components</span></my-card><script> class MyCard extends HTMLElement { constructor () { super(); const template = document.getElementById('cardTmp'); const templateContent = template.content; this.attachShadow({mode: 'open'}).appendChild( templateContent.cloneNode(true) ); } } customElements.define('my-card', MyCard);</script>
Running effect:
Because the incoming slot attribute value does not match the name attribute value of Slots, so Slots is not is inserted.
The slot attribute value when passing the value must be consistent with the name attribute value of Slots.
What happens if you don’t pass a value to Slots?
Remove the span element in the above two custom elements my-card
and do not pass any value, that is, change it to this:
<my-card></my-card>
The effect after running:
As you can see, if no value is passed to Slots, then Slots will display its own preset content.
In fact, combining the above two points, we can also draw a conclusion: If there is a reference to Slots, only the content of the Slots corresponding to the name will be displayed, and the remaining Slots will not be displayed.
Can Slots be used in normal DOM?
The "normal DOM" here is relative to Shadow DOM and refers to the document object where the page is located.
The code is as follows:
<slot>Slots 预设值</slot><p>bcsm</p>
is displayed as follows:
Summary: Using Slots in normal DOM, it will be rendered directly in On the page, there is no slot effect.
Do Slots have to be used in Templates?
In the example we saw earlier, Slots are in Templates. Does that mean that Slots must be used in Templates to take effect?
Because it has been verified that Slots in normal DOM are invalid, so we do a test in Shadow DOM. The code is as follows:
<h1 id="不在-Templates-中使用-Slots">不在 Templates 中使用 Slots</h1> <p> <slot>这是 Slots 预设值</slot> </p> <my-paragraph> <span>编程三昧</span> </my-paragraph> <script> class MyParagraph extends HTMLElement { constructor () { super(); const template = document.getElementById('templ'); this.attachShadow({mode: 'open'}).appendChild( template.cloneNode(true) ); } } customElements.define('my-paragraph', MyParagraph); </script>
The display effect is as follows:
You can see from the display effect that after appending the normal DOM node containing Slots to the Shadow DOM, the Slots display the incoming value, which means that the Slots are effective.
Summary: Slots can take effect in Shadow DOM and do not have to be used in Templates.
Can multiple Slots with the same name be used in a custom element?
Look at the code:
<template> <p>MY CARD</p> <p> My name is <slot>编程三昧</slot>。 </p></template><my-card> <span>插槽传值1</span> <span>插槽传值2</span></my-card><script> class MyCard extends HTMLElement { constructor () { super(); const template = document.getElementById('cardTmp'); const templateContent = template.content; this.attachShadow({mode: 'open'}).appendChild( templateContent.cloneNode(true) ); } } customElements.define('my-card', MyCard);</script>
Display effect:
Conclusion: A Slots can receive multiple incoming values, and It will be parsed and displayed .
Slots 的传值元素必须是自定义元素的直接子元素吗?
上面的例子中,所有给 Slots 传值的元素都是自定义元素的子元素,那是不是非直接子元素不行呢?
代码如下:
<template> <p>MY CARD</p> <p> My name is <slot>编程三昧</slot>。 </p></template><my-card> <p> <span>插槽传值1</span> </p></my-card><script> class MyCard extends HTMLElement { constructor () { super(); const template = document.getElementById('cardTmp'); const templateContent = template.content; this.attachShadow({mode: 'open'}).appendChild( templateContent.cloneNode(true) ); } } customElements.define('my-card', MyCard);</script>
运行效果(传值失效):
结论:给 Slots 传值的元素必须是自定义元素的直接子元素,否则传值失效。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Let's talk about Slots of Web Components (detailed examples). For more information, please follow other related articles on the PHP Chinese website!

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

IDsshouldbeusedforJavaScripthooks,whileclassesarebetterforstyling.1)Useclassesforstylingtoallowforeasierreuseandavoidspecificityissues.2)UseIDsforJavaScripthookstouniquelyidentifyelements.3)Avoiddeepnestingtokeepselectorssimpleandimproveperformance.4

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
