Home Web Front-end JS Tutorial Detailed explanation of the use of slots/scoped in Vue

Detailed explanation of the use of slots/scoped in Vue

May 02, 2018 pm 01:42 PM
Detailed explanation

This time I will bring you a detailed explanation of the use of slots/scoped in Vue. What are the precautions for using slots/scoped in Vue. Here are practical cases, let’s take a look.

The following is an example to briefly explain the working principle of slots

The template of the dx-li subcomponent is as follows:

<li class="dx-li">
 <slot>
   你好!
 </slot>
</li>
dx-ul父组件的template如下:
<ul>
 <dx-li>
  hello juejin!
 </dx-li>
</ul>
结合上述例子以及vue中相关源码进行分析
dx-ul父组件中template编译后,生成的组件render函数:
module.exports={
 render:function (){
  var _vm=this;
  var _h=_vm.$createElement;
  var _c=_vm._self._c||_h;
  // 其中_vm.v为createTextVNode创建文本VNode的函数
  return _c('ul', 
    [_c('dx-li', [_vm._v("hello juejin!")])],
    1)
 },
 staticRenderFns: []
}
Copy after login

The passed slot content 'hello juejin!' will be compiled into a child node of the dx-li sub-component VNode node.

Render the dx-li subcomponent, in which the render function of the subcomponent:

module.exports={
 render:function (){
  var _vm=this;
  var _h=_vm.$createElement;
  var _c=_vm._self._c||_h;
  // 其中_vm._v 函数为renderSlot函数
  return _c('li', 
    {staticClass: "dx-li" }, 
    [_vm._t("default", [_vm._v("你好 掘金!")])], 
    2
   )
  },
 staticRenderFns: []
}
Copy after login

During the process of initializing the vue instance of the dx-li subcomponent, the initRender function will be called:

function initRender (vm) {
 ...
 // 其中_renderChildren数组,存储为 'hello juejin!'的VNode节点;renderContext一般为父组件Vue实例
 这里为dx-ul组件实例
 vm.$slots = resolveSlots(options._renderChildren, renderContext);
 ...
}
Copy after login

The resolveSlots function is:

/**
 * 主要作用是将children VNodes转化成一个slots对象.
 */
export function resolveSlots (
 children: ?Array<VNode>,
 context: ?Component
): { [key: string]: Array<VNode> } {
 const slots = {}
 // 判断是否有children,即是否有插槽VNode
 if (!children) {
 return slots
 }
 // 遍历父组件节点的孩子节点
 for (let i = 0, l = children.length; i < l; i++) {
 const child = children[i]
 // data为VNodeData,保存父组件传递到子组件的props以及attrs等
 const data = child.data
 /* 移除slot属性
 * <span slot="abc"></span> 
 * 编译成span的VNode节点data = {attrs:{slot: "abc"}, slot: "abc"},所以这里删除该节点attrs的slot
 */
 if (data && data.attrs && data.attrs.slot) {
  delete data.attrs.slot
 }
 /* 判断是否为具名插槽,如果为具名插槽,还需要子组件/函数子组件渲染上下文一致。主要作用:
 *当需要向子组件的子组件传递具名插槽时,不会保持插槽的名字。
 * 举个栗子:
 * child组件template: 
 * <p>
 * <p class="default"><slot></slot></p>
 * <p class="named"><slot name="foo"></slot></p>
 * </p>
 * parent组件template:
 * <child><slot name="foo"></slot></child>
 * main组件template:
 * <parent><span slot="foo">foo</span></parent>
 * 此时main渲染的结果:
 * <p>
 * <p class="default"><span slot="foo">foo</span></p>
   <p class="named"></p>
 * </p>
 */
 if ((child.context === context || child.fnContext === context) &&
  data && data.slot != null
 ) {
  const name = data.slot
  const slot = (slots[name] || (slots[name] = []))
  // 这里处理父组件采用template形式的插槽
  if (child.tag === 'template') {
  slot.push.apply(slot, child.children || [])
  } else {
  slot.push(child)
  }
 } else {
  // 返回匿名default插槽VNode数组
  (slots.default || (slots.default = [])).push(child)
 }
 }
 // 忽略仅仅包含whitespace的插槽
 for (const name in slots) {
 if (slots[name].every(isWhitespace)) {
  delete slots[name]
 }
 }
 return slots
}
Copy after login

Then when the dx-li component is mounted, the dx-li component render function will be called. In the process, the renderSlot function will be called:

export function renderSlot (
  name: string, // 子组件中slot的name,匿名default
  fallback: ?Array<VNode>, // 子组件插槽中默认内容VNode数组,如果没有插槽内容,则显示该内容
  props: ?Object, // 子组件传递到插槽的props
  bindObject: ?Object // 针对<slot v-bind="obj"></slot> obj必须是一个对象
 ): ?Array<VNode> {
 // 判断父组件是否传递作用域插槽
  const scopedSlotFn = this.$scopedSlots[name]
  let nodes
  if (scopedSlotFn) { // scoped slot
  props = props || {}
  if (bindObject) {
   if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) {
   warn(
    'slot v-bind without argument expects an Object',
    this
   )
   }
   props = extend(extend({}, bindObject), props)
  }
  // 传入props生成相应的VNode
  nodes = scopedSlotFn(props) || fallback
  } else {
  // 如果父组件没有传递作用域插槽
  const slotNodes = this.$slots[name]
  // warn duplicate slot usage
  if (slotNodes) {
   if (process.env.NODE_ENV !== 'production' && slotNodes._rendered) {
   warn(
    `Duplicate presence of slot "${name}" found in the same render tree ` +
    `- this will likely cause render errors.`,
    this
   )
   }
   // 设置父组件传递插槽的VNode._rendered,用于后面判断是否有重名slot
   slotNodes._rendered = true
  }
  // 如果没有传入插槽,则为默认插槽内容VNode
  nodes = slotNodes || fallback
  }
  // 如果还需要向子组件的子组件传递slot
  /*举个栗子:
  * Bar组件: <p class="bar"><slot name="foo"/></p>
  * Foo组件:<p class="foo"><bar><slot slot="foo"/></bar></p>
  * main组件:<p><foo>hello</foo></p>
  * 最终渲染:<p class="foo"><p class="bar">hello</p></p>
  */
  const target = props && props.slot
  if (target) {
  return this.$createElement('template', { slot: target }, nodes)
  } else {
  return nodes
  }
 }
Copy after login

scoped slots understanding

The template of the dx-li subcomponent is as follows:

<li class="dx-li"> 
 <slot str="你好 掘金!">
  hello juejin!
 </slot>
</li>
dx-ul父组件的template如下:
<ul>
 <dx-li>
  <span slot-scope="scope">
   {{scope.str}}
  </span>
 </dx-li>
</ul>
结合例子和Vue源码简单作用域插槽
dx-ul父组件中template编译后,产生组件render函数:
module.exports={
 render:function (){
  var _vm=this;
  var _h=_vm.$createElement;
  var _c=_vm._self._c||_h;
   return _c('ul', [_c('dx-li', {
   // 可以编译生成一个对象数组
   scopedSlots: _vm._u([{
    key: "default",
    fn: function(scope) {
    return _c('span', 
     {},
     [_vm._v(_vm._s(scope.str))]
    )
    }
   }])
   })], 1)
  },
 staticRenderFns: []
 }
Copy after login

The _vm._u function:

function resolveScopedSlots (
 fns, // 为一个对象数组,见上文scopedSlots
 res
) {
 res = res || {};
 for (var i = 0; i < fns.length; i++) {
  if (Array.isArray(fns[i])) {
   // 递归调用
   resolveScopedSlots(fns[i], res);
  } else {
   res[fns[i].key] = fns[i].fn;
  }
 }
 return res
}
Copy after login

The subsequent rendering process of the subcomponent is similar to slots. The principle of scoped slots is basically the same as that of slots. The difference is that when compiling the parent component template, a function that returns a VNode will be generated. When the child component matches the scope slot function passed by the parent component, the function is called to generate the corresponding VNode.

Summary

In fact, the principle of slots/scoped slots is very simple. We only need to understand that when vue renders components, it is based on VNode Renders actual DOM elements.

Slots are slot VNodes generated by compiling parent components. When rendering sub-components, they are placed in the corresponding sub-component rendering VNode tree.

scoped slots compiles the slot content in the parent component into a function. When rendering the sub-component, pass in the sub-component props and generate the corresponding VNode. Finally, the subcomponent returns the VNode node tree according to the component render function, and updates to render the real DOM elements. At the same time, it can be seen that passing slots across components is also possible, but care must be taken to pass named slots.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to split the page code and load it on demand

Detailed explanation of the use of slot sockets in the vue component

The above is the detailed content of Detailed explanation of the use of slots/scoped in Vue. For more information, please follow other related articles on the PHP Chinese website!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the mode function in C++ Detailed explanation of the mode function in C++ Nov 18, 2023 pm 03:08 PM

Detailed explanation of the mode function in C++ In statistics, the mode refers to the value that appears most frequently in a set of data. In C++ language, we can find the mode in any set of data by writing a mode function. The mode function can be implemented in many different ways, two of the commonly used methods will be introduced in detail below. The first method is to use a hash table to count the number of occurrences of each number. First, we need to define a hash table with each number as the key and the number of occurrences as the value. Then, for a given data set, we run

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of remainder function in C++ Detailed explanation of remainder function in C++ Nov 18, 2023 pm 02:41 PM

Detailed explanation of the remainder function in C++ In C++, the remainder operator (%) is used to calculate the remainder of the division of two numbers. It is a binary operator whose operands can be any integer type (including char, short, int, long, etc.) or a floating-point number type (such as float, double). The remainder operator returns a result with the same sign as the dividend. For example, for the remainder operation of integers, we can use the following code to implement: inta=10;intb=3;

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates Jul 26, 2023 am 08:57 AM

Detailed explanation of the usage of Vue.nextTick function and its application in asynchronous updates. In Vue development, we often encounter situations where data needs to be updated asynchronously. For example, data needs to be updated immediately after modifying the DOM or related operations need to be performed immediately after the data is updated. The .nextTick function provided by Vue emerged to solve this type of problem. This article will introduce the usage of the Vue.nextTick function in detail, and combine it with code examples to illustrate its application in asynchronous updates. 1. Vue.nex

Detailed explanation of php-fpm tuning method Detailed explanation of php-fpm tuning method Jul 08, 2023 pm 04:31 PM

PHP-FPM is a commonly used PHP process manager used to provide better PHP performance and stability. However, in a high-load environment, the default configuration of PHP-FPM may not meet the needs, so we need to tune it. This article will introduce the tuning method of PHP-FPM in detail and give some code examples. 1. Increase the number of processes. By default, PHP-FPM only starts a small number of processes to handle requests. In a high-load environment, we can improve the concurrency of PHP-FPM by increasing the number of processes

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed analysis of C language learning route Detailed analysis of C language learning route Feb 18, 2024 am 10:38 AM

As a programming language widely used in the field of software development, C language is the first choice for many beginner programmers. Learning C language can not only help us establish the basic knowledge of programming, but also improve our problem-solving and thinking abilities. This article will introduce in detail a C language learning roadmap to help beginners better plan their learning process. 1. Learn basic grammar Before starting to learn C language, we first need to understand the basic grammar rules of C language. This includes variables and data types, operators, control statements (such as if statements,

See all articles