This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Scope slot

We can use scope slots to give the parent component’s slot content access to the child component’s data, which is recorded as properties in the child component. The parent component gets the values passed by the child component in the form of V-slot :[name]=[props]. The features on the sub-component

element are called slot Props, and slot-scoped has been deprecated in vue2.6 and v-slot has been used instead.

var child = {
  template: `<div><slot :user="user"></div>`,
  data() {
    return {
      user: {
        firstname: 'test'
      }
    }
  }
}
var vm = new Vue({
  el: '#app',
  components: {
    child
  },
  template: `<div id="app"><child><template v-slot:default="slotProps">{{slotProps.user.firstname}}</template></child></div>`
})

Copy the code

Scoped slots work in a similar way to named slots, so let’s move on.

Parent component compilation phase

The use of scoped slot and named slot in the parent component is basically the same. The difference is that v-slot defines the name of a slot props. In the render generation phase of the named slot, the fn function carries the props parameter. That is:

with(this){return _c('div',{attrs:{"id":"app"}},[_c('child',
{scopedSlots:_u([{key:"default",fn:function(slotProps){return 
[_v(_s(slotProps.user.firstname))]}}])})],1)}

Copy the code

Subcomponent rendering

During subcomponent compilation, :user=”user” is parsed as a property, and finally _t is passed as an object parameter during render function generation.

with(this){return _c('div',[_t("default",null,{"user":user})],2)}

Copy the code

The renderSlot function is executed in the Vnode rendering phase of the sub-component. As previously analyzed, the processing of the scope slot is mainly reflected in the third parameter passed in the function.

Function renderSlot(name, fallback, props, // child to parent {user: Var scopedSlotFn = this.$scopedSlots[name]; var nodes; A named slot branch if (scopedSlotFn) {/ / / / scoped slot props = props | | {}; if (bindObject) { if (! isObject(bindObject)) { warn( 'slot v-bind without argument expects an Object', this ); } // merge props = extend(extend({}, bindObject), props); } / / execution when the child component to the value of the parent component into the fn nodes = scopedSlotFn (props) | | fallback. }Copy the code

Finally, the socket props of the child component is passed as an argument to the execution function. Take a look back at why named slots are executed as functions rather than returning results directly. After studying the scope slot, we found that this is the clever part of the design. The form of function makes the execution process more flexible. The scope slot only needs to pass the slot props as a parameter to get the desired result.