Home > Web Front-end > Vue.js > In-depth understanding of slots, content distribution, and named slots in Vue

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

青灯夜游
Release: 2022-10-12 19:43:32
forward
2132 people have browsed it

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>`
}
Copy after login
  • 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

//普通的组件定义
Copy after login
        
  •     {{ 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>
Copy after login
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>
Copy after login
    Data reception
  • Default slot reception
    //父组件 - 使用方
    <mycom>
      {{ shopInfo }} {{ userInfo }}
    </mycom>
    Copy after login
    • Named slot reception
    <mycom>
      <template>
        {{ shopInfo }}
      </template>
    
      <template>
        {{ introduction }}
      </template>
    
      <template>
        {{ userInfo }}
      </template>
    </mycom>
    Copy after login
      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>
    Copy after login
  • 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
    • <div class="code" style="position:relative; padding:0px; margin:0px;"><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><div class="contentsignin">Copy after login</div></div>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>
    Copy after login
    动态组件

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

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

    拓展

    components的第二种写法

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

    <div>
        <cpn></cpn>
    </div>
    <template>
        <div>
            <h2>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>
    Copy after login

    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>
      Copy after login
      let template = document.getElementById('my-paragraph');
      let templateContent = template.content;
      document.body.appendChild(templateContent);
      Copy after login
      • 可以配合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>
      Copy after login
      • 后续的样式逻辑也需要加在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' }
          );
          Copy after login

          可以使用ES2015的类实现

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

        • 类型一: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
      Copy after login
      • 当需要将一个shadow DOM添加到自定义的标签上时,可以在自定义的构造函数中添加如下逻辑;
      let shadow = this.attachShadow({mode: 'open'});
      // 将一个shadow DOM添加到一个元素上之后就可以使用DOM API进行操作访问了
      Copy after login

    (学习视频分享: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!

  • Related labels:
    vue
    source:juejin.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template