Home> Web Front-end> Vue.js> body text

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

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

This article will share with youVueadvanced 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 `` }
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 thenameattribute 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-slotcan be abbreviated to#, whose value corresponds to thein the slot The value corresponding to name;
  • When there are both default slots and named slots in a component, all top-level non-
  • templatenodes are implicitly considered The contents of the default slot, so thetemplatenode label of the default slot can be omitted;
     
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) - throughslot
The props passed into the slot by the sub-component are used as the value of thev-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

//子组件 
Copy after login
    Data reception
  • Default slot reception
    //父组件 - 使用方  {{ shopInfo }} {{ userInfo }} 
    Copy after login
    • Named slot reception
        
    Copy after login
      When using slot-scope, replace the slot in the template with the last slot-scope
      
    555
    {{scope.name}}
    {{scope}}
    {{scope.name}}
    {{scope.age}}
    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
    • // 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' } // ] // } <my-list> <template> <div>{{ shape.name }} <small>({{ shape.sides }} sides)</small> </div> </template> </my-list> <my-list> <template> <div> <div></div> {{ color.name }} </div> </template> </my-list> <div> <div>{{ title }}</div> <div> <div> <slot></slot> </div> </div> </div> Vue.component('my-list', { template: '#my-list', props: [ 'title', 'items' ] });
      Copy after login
      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属性
      • 需要有一个明确的结束条件
     
    Copy after login
    动态组件

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

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

    拓展

    components的第二种写法

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

    Copy after login

    Web Component简介

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

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

    • 模板 - Templates

      • 需要在网页上重复的使用相同的标记结构时,为了避免CV的操作可以通过模板的方式进行实现
      • 需要注意的是模板 - Template 和其内部的内容是不会在DOM中呈现的,可以通过js进行访问并添加到DOM中,从而在界面上进行展示
      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)); } }) // 自定义标签使用 
      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使用,也可以通过js的方式进行使用document.createElement("popup-info")
        • 类型二:Customized built-in elements继承自基本的 HTML 元素。在创建时,你必须指定所需扩展的元素,使用时,需要先写出基本的元素标签,并通过is属性指定 custom element 的名称;

          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