Scope slot format, examples, and how it works

What it does: Gives slot content access to data in child components.

Formatting: Formatting is described in two sections, one for defining child components and the other for using in parent components.

When defining a child component, bind props to slot

/ / child component
Vue.component('com1', {  
template: ` < div > < h6 > I am a child component < h6 > < slot: num = "num" > < / slot > < / div > `
})
Copy the code

When a child component is used in a parent component, the slot container receives data thrown from the slot in the child component through a slot-scope.

<div>
 <com1>    
  <div slot-scope="scope">
    {{scope}}     
   </div> 
 </com1>
</div>
Copy the code

Example:

Vue.component('com1', {   
  data() {
  return { num: 100}},template: ` < div > < h6 > I am a child component < h6 > < slot: num = "num" > < / slot > < / div > ` 
  })
Copy the code

The point is that the default slot slot has a property called num bound to it, which is the data THAT I want to pass back to the container that uses the slot.

Here is some sample code using this subcomponent:

<div id="app">
  <com1>
    <div>nihao</div>
  </com1>
  <hr/>
  <com1>
    <div slot-scope="scope">
      nihao-{{scope.num}}
    </div>
  </com1>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.js"></script>
<script>
  new Vue({
    el: "#app"
  })
</script>
Copy the code

The result is as follows:

Effects of a scoped slot:

In the child component, slot properties are bound, and then in the parent component, these properties are collected by slot-scope. After collecting these properties, the content is assembled according to the specific business logic to fill the slot area of the child component.

  • In the child component, the internal data includes props, data, computed, and so on, all of which can be properly bound to slot.
  • In a child component, multiple properties can be bound to slot, and these properties are automatically collected to the object scope specified after slot-scope in the parent component, assuming that on the child component<slot :num="num" :a="1"></slot>, then the value of the parent component scope is{num: 100, a: 1}
  • Slot can also be a named slot in a child component.

understand

The scope slot gives parent and child components more flexibility when they are used.

  • Father to son, data to son.

< subcomponent :prop1="num1"></ subcomponent >

  • From father to son, structure to son.
< subcomponent ><template>Custom structure where data in the parent component can be accessed</template></ subcomponent >Copy the code
  • Parent to child, structure, structure based on the data in the child component.
< subcomponent ><template slot-scope="dataFromSon">Custom structure, where you can access the data returned by the child component, dataFromSon</template></ subcomponent >Copy the code