search
HomeWeb Front-endVue.jsIn-depth understanding of slots, content distribution, and named slots in Vue

This article will share with you Vue advanced skills and a deep understanding of slots, content distribution, and named slots in Vue. I hope it will be helpful to everyone.

In-depth understanding of slots, content distribution, and named slots in Vue

Introduction to Slots

The data of components in Vue can be passed through props or events. Get and pass, but when you need to receive template content (any legal template content, code snippets, Vue components), you need to use slots to achieve it. Of course, it can also be achieved indirectly through functional programming; [Related recommendation: vuejs video tutorial]

In-depth understanding of slots, content distribution, and named slots in Vue

  • You can understand the slot Compile for functions in js
// 父元素传入插槽内容
FancyButton('Click me!')

// FancyButton 在自己的模板中渲染插槽内容
function FancyButton(slotContent) {
    return `<button>
      ${slotContent}
    </button>`
}
  • The best way to encapsulate is to extract commonalities into components and expose differences as slots - extract commonalities and retain differences
  • Everything in the parent component template will be compiled in the parent component scope, and everything in the child component template will be compiled in the child component scope - Compilation scope

slot-scope shallow Analysis

Conventional slots can be used to customize component templates, but they are only limited to fixed templates and cannot customize specific internal items, that is, conventional slots cannot be implemented. Different content distribution for each item in the component loop can be implemented through slot-scope. It is essentially the same as slot. The difference is that parameters can be passed

//普通的组件定义
        
  •     {{ book.name }}     
//slot-scope组件定义
        
  •                                   {{ book.name }}              
//父组件使用     

When using slot-scope, when the parent component uses this API, the corresponding slot will replace the slot in the template for display

A brief analysis of common APIs

Named Slot

Defining multiple slot exits in the component can be compatible with multiple different requirements, allowing the contents of multiple slots to be passed into their respective slots In the exit; when the name attribute is configured in a slot, the slot is called a named slot. Slots without a name will be implicitly named "default"

In-depth understanding of slots, content distribution, and named slots in Vue

  • ##v-slot can be abbreviated to #, whose value corresponds to the in the slot The value corresponding to name;
  • When there are both default slots and named slots in a component, all top-level non-
  • template nodes are implicitly considered The contents of the default slot, so the template node label of the default slot can be omitted;
<com>
    <!-- 隐式的默认插槽 -->
    <!-- <p>A paragraph for the main content.</p>
    <p>And another one.</p> -->
    <template>
        <p>A paragraph for the main content.</p>
        <p>And another one.</p>
    </template>
    <template>
        <p>Here's some contact info</p>
    </template>
</com>
scope slot
Ordinary slots cannot obtain data in other scopes, that is,

Expressions in the parent component template can only access the scope of the parent component; expressions in the child component template can only access child components. The scope of The component provides part of the data to the slot when rendering, so that the data in the child component can be used outside the component (parent component) - through slot
The props passed into the slot by the sub-component are used as the value of the v-slot

directive, which can be accessed in the expression in the slot, where name is an attribute specially reserved by Vue and will not be used as props Make a transfer

Data transfer

//子组件
<template> 
    <slot></slot> 
</template>
    Data reception
  • Default slot reception
    //父组件 - 使用方
    <mycom>
      {{ shopInfo }} {{ userInfo }}
    </mycom>
    • Named slot reception
    <mycom>
      <template>
        {{ shopInfo }}
      </template>
    
      <template>
        {{ introduction }}
      </template>
    
      <template>
        {{ userInfo }}
      </template>
    </mycom>
      When using slot-scope, replace the slot in the template with the last slot-scope
    <cpm>
        <!-- 不显示 -->
        <div>555</div>
        <!-- 不显示 -->
        <div>
            <div>{{scope.name}}</div>
        </div>
        <!-- 显示 -->
        <div>
            <div>{{scope}}</div>
            <div>{{scope.name}}</div>
            <div>{{scope.age}}</div>
        </div>
    </cpm>
  • When using scope slots, you can reuse subcomponent slots and make the contents of slots inconsistent. It allows users to pass a template instead of already rendered elements to the slot. The so-called scope refers to the template. Although it is rendered in the parent scope, the data of the child component can be obtained.
  • Conventional v-bind needs to carry the parameter key value for transmission, for example, v-bind:info = '123 '
      ; But sometimes this key value is omitted and the data is transferred directly, such as
    • v-bind = 'item'
    • . This usage will bind all attributes of the entire object to the current element. Suitable for scenarios where there are too many properties that need to be bound
    • <pre class="brush:php;toolbar:false">// data: { //     shapes: [ //         { name: 'Square', sides: 4 }, //         { name: 'Hexagon', sides: 6 }, //         { name: 'Triangle', sides: 3 } //     ], //     colors: [ //         { name: 'Yellow', hex: '#F4D03F', }, //         { name: 'Green', hex: '#229954' }, //         { name: 'Purple', hex: '#9B59B6' } //     ] // } &lt;my-list&gt;     &lt;template&gt;         &lt;div&gt;{{ shape.name }} &lt;small&gt;({{ shape.sides }} sides)&lt;/small&gt; &lt;/div&gt;     &lt;/template&gt; &lt;/my-list&gt; &lt;my-list&gt;     &lt;template&gt;         &lt;div&gt;             &lt;div&gt;&lt;/div&gt;             {{ color.name }}         &lt;/div&gt;     &lt;/template&gt; &lt;/my-list&gt; &lt;div&gt;     &lt;div&gt;{{ title }}&lt;/div&gt;     &lt;div&gt;         &lt;div&gt;             &lt;slot&gt;&lt;/slot&gt;         &lt;/div&gt;     &lt;/div&gt; &lt;/div&gt; Vue.component('my-list', {     template: '#my-list',     props: [ 'title', 'items' ] });</pre>Recursive component
    Recursive component means that the component calls itself in the template , since it is called by the component itself, it cannot omit the name configuration of the component like a regular component definition. The recursion of the component needs to depend on its own name configuration (name is also used to traverse the name option of the component to find the instance of the component);
    • 满足条件
      • 需要给组件设置一个name属性
      • 需要有一个明确的结束条件
    <template>
        <div>
            <my-component></my-component>
        </div>
    </template>
    <script>
    export default {
        name:&#39;my-component&#39;,
        props: {
            count: {
                type: Number,
                default: 1
            }
        }
    }
    </script>
    动态组件

    有时候我们需要根据一些条件,动态的切换/选择某个组件,在函数式组件中,没有上下文的概念,常用于程序化的在多个组件中选择一个,可以间接的解决动态切换组件的需求,缺点是基于js对象进行开发,不方便开发;
    Vue官方提供了一个内置组件<component></component>和is的属性,用来解决上述的问题

    <component></component>
    //component 就是js import进的组件实例,其值可以是标签名、组件名、直接绑定一个对象等
    • 为了使得组件具有缓存作用,可以使用的内置组件,这样只要不离开当前页面,切换到其他组件后deforeDestory不会执行,因此组件具有了缓存功能

    拓展

    components的第二种写法

    常规的组件components是直接通过引用定义好的组件进行展示的,也可以直接在当前组件内定义,然后通过配置components进行渲染

    <div>
        <cpn></cpn>
    </div>
    <template>
        <div>
            <h2 id="Lbxin">Lbxin</h2>
            <p>class - 11</p>
        </div>
    </template>
    <script>
    var app = new Vue({
        el: &#39;#app&#39;,
        data: {
            isShow: true
        },
        components: {
            cpn: {
                template: &#39;#com&#39;,
                data() {
                    isShow: false
                }
            }
        }
    })
    </script>

    Web Component <slot></slot> 简介

    HTML的slot元素,是Web Components技术套件的一部分,是Web组件内的一个占位符,该占位符可以在后期使用自己的标记语言进行填充,这样可以创建单独的DOM树,并将其与其他的组件组合在一起 -- MDN

    常见的填充Web组件的shadow DOM的模板有template和slot

    • 模板 - Templates

      • 需要在网页上重复的使用相同的标记结构时,为了避免CV的操作可以通过模板的方式进行实现
      • 需要注意的是模板 - Template 和其内部的内容是不会在DOM中呈现的,可以通过js进行访问并添加到DOM中,从而在界面上进行展示
      <template>
        <p>My paragraph</p>
      </template>
      let template = document.getElementById('my-paragraph');
      let templateContent = template.content;
      document.body.appendChild(templateContent);
      • 可以配合Web Component一起使用,实现纯js自定义的组件
      customElements.define('my-paragraph',
        class extends HTMLElement {
          constructor() {
            super();
            let template = document.getElementById('my-paragraph');
            let templateContent = template.content;
      
            const shadowRoot = this.attachShadow({mode: 'open'})
              .appendChild(templateContent.cloneNode(true));
        }
      })
      
      // 自定义标签使用
      <my-paragraph></my-paragraph>
      • 后续的样式逻辑也需要加在template中,方便通过后续的相关逻辑(如template.content获取到然后打入到指定的容器中)
    • Web Component简介

      • Web Component的一个很重要的属性就是封装 - 可以将标记结构、样式和行为影藏起来,并于界面上的其他代码隔离开来,保证代码的独立性

      • Web Component标准非常重要的一个特性是,使得开发者可以将HTML页面的功能封住成custom elements(自定义标签)

      • customElements 接口用来实现一个对象,允许开发者注册一个custom elements的信息,返回已注册的自定义标签的信息;

      • customElements.define方法用来注册一个custom element,接收三个参数

        • 参数一:表明创建元素的名称,其注册的名称不能简单的单词,需要由短划线进行拼接

        • 参数二:用于定义元素行为的类

        • 参数三:一个包含extends属性配置的配置对象,可选,指定了所创建的自定义元素是继承于哪个内置的元素,可以继承任何内置的元素;

          customElements.define(
              'word-count', 
              WordCount, 
              { extends: 'p' }
          );

          可以使用ES2015的类实现

          class WordCount extends HTMLParagraphElement {
            constructor() {
              // 必须首先调用 super 方法
              super();
              // 元素的功能代码写在这里
              ...
            }
          }
      • 自定义标签的类型

        • 类型一:Autonomous custom elements 是独立的元素,它不继承其他内建的 HTML 元素,可以直接通过标签的方式进行HTML使用<popup-info></popup-info>,也可以通过js的方式进行使用document.createElement("popup-info")
        • 类型二:Customized built-in elements 继承自基本的 HTML 元素。在创建时,你必须指定所需扩展的元素,使用时,需要先写出基本的元素标签,并通过 is属性指定 custom element 的名称;<p is="word-count"></p>document.createElement("p", { is: "word-count" })

        参考文献 - MDN

    • shadow DOM简介

      • 图解Shandow DOM

      In-depth understanding of slots, content distribution, and named slots in Vue

      • Shadow host:一个常规 DOM 节点,Shadow DOM 会被附加到这个节点上。

      • Shadow tree:Shadow DOM 内部的 DOM 树。

      • Shadow boundary:Shadow DOM 结束的地方,也是常规 DOM 开始的地方。

      • Shadow root: Shadow tree 的根节点。

      shadow DOM主要是将一个隐藏的、独立的DOM树附加到常规的DOM树上,是以shadow DOM节点为起始根节点,在这个根节点的下方,可以是任意的元素,和普通的DOM元素一致

    如常见的video标签,其内部的一些控制器和按钮等都是通过Shandow DOM进行维护的,开发者可以通过这个API进行自己独立的逻辑控制

    • 基本用法

      • Element.attachShadow()方法可以将一个shadow DOM添加到任何一个元素上,接收一个配置对象参数,该对象有一个mode的属性,值可以是open - 可以通过外部js获取 Shadow DOM和closed - 外部不可以通过js进行获取 Shadow DOM
      let shadow1 = elementRef.attachShadow({mode: 'open'});
      let shadow2 = elementRef.attachShadow({mode: 'closed'});
      let myShadowDom = shadow1.shadowRoot; // 具体内容
      let myShadowDom = shadow2.shadowRoot; //null
      • 当需要将一个shadow DOM添加到自定义的标签上时,可以在自定义的构造函数中添加如下逻辑;
      let shadow = this.attachShadow({mode: 'open'});
      // 将一个shadow DOM添加到一个元素上之后就可以使用DOM API进行操作访问了

    (学习视频分享:web前端开发编程基础视频

    The above is the detailed content of In-depth understanding of slots, content distribution, and named slots in Vue. For more information, please follow other related articles on the PHP Chinese website!

  • Statement
    This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
    Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

    Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

    Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

    Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

    Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

    Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

    Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

    Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

    The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

    Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

    React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

    Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

    The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

    Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

    React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

    Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.