search
HomeWeb Front-endJS TutorialDetailed explanation of the use of slots/scoped in Vue

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:


  •      你好!  
  • dx-ul父组件的template如下:
          hello juejin!  
    结合上述例子以及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: [] }

    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: []
    }

    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);
     ...
    }

    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  
     * 编译成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>
    <p><slot></slot></p>
     * <p><slot></slot></p>
     * 
     * parent组件template:
     * <child><slot></slot></child>
     * main组件template:
     * <parent><span>foo</span></parent>
     * 此时main渲染的结果:
     * <p>
     * </p>
    <p><span>foo</span></p>
       <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
    }</vnode></vnode>

    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></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><slot></slot></p>
      * Foo组件:<p><bar><slot></slot></bar></p>
      * main组件:<p><foo>hello</foo></p>
      * 最终渲染:<p></p>
    <p>hello</p>
      */
      const target = props && props.slot
      if (target) {
      return this.$createElement('template', { slot: target }, nodes)
      } else {
      return nodes
      }
     }</vnode></vnode>

    scoped slots understanding

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

    
    
  •       hello juejin!  
  • dx-ul父组件的template如下:
              {{scope.str}}     
    结合例子和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: []  }

    The _vm._u function:

    function resolveScopedSlots (
     fns, // 为一个对象数组,见上文scopedSlots
     res
    ) {
     res = res || {};
     for (var i = 0; i <p style="text-align: left;">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. </p><p style="text-align: left;"><span style="color: #ff0000"><strong>Summary</strong></span></p><p style="text-align: left;">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. </p><p style="text-align: left;">Slots are slot VNodes generated by compiling parent components. When rendering sub-components, they are placed in the corresponding sub-component rendering VNode tree. </p><p style="text-align: left;">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. </p><p> 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! </p><p>Recommended reading: </p><p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-394904.html" target="_blank">How to split the page code and load it on demand</a><br></p><p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-394902.html" target="_blank">Detailed explanation of the use of slot sockets in the vue component</a><br></p>

    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
    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
    The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

    Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

    Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

    Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

    Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

    The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

    The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

    JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

    Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

    JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

    The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

    The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

    Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

    Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

    Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

    Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

    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

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.