The basic use and value transfer of slots (anonymous slots, named slots, scoped slots) in vue (child to parent)

The basic use and value transfer of slots (anonymous slots, named slots, scoped slots) in vue (child to parent)

1. What is a slot?
The slot is a placeholder in the child component that is provided to the parent component. It means that the parent component can fill any template code in this placeholder, such as HTML, component, etc. The filled content will replace the label of the child component .

Don’t say much, go directly to the case

Parent component:

<template>
<div class="father" style="background:yellow;width:500px" >
<h3>我是黄色背景的父组件</h3>
 <Chacao>
    <div slot="chaCao1" style="border:1px solid green">
      我是具名插槽(绿色边框)
    </div>
    <div slot="chaCao2" slot-scope="jie" style="border:1px solid blue">
     我是带有传值的作用域插槽(蓝色边框):<br>
      <span v-for="(item,index) in jie.chuan" :key="index">姓名:{
   
   {item.name}} 性别:{
   
   {item.sex}} 年龄:{
   
   {item.age}}</span>
    </div>
    <div style="border:1px solid pink">
      我是粉色边框的匿名插槽
    </div>
  </Chacao>
</div>
</template>

<script>
import Chacao from '../components/Login/chacao.vue'
export default {
  data(){
    return{
    }
  },
  components:{
    Chacao
  }
}
</script>

Subassembly:

<template>
  <div class="child" style="border:1px solid red">
    <h3>我是红色边框的子组件</h3>
    <slot name="chaCao1"></slot>
    <slot name="chaCao2" :chuan="arr"></slot>
    <slot></slot>
  </div>
</template>

<script>
export default {
  
  data(){
    return{
      arr:[
        {"name":"张三","sex":"男","age":18},
        {"name":"李四","sex":"男","age":28},
        ]
    }
  }
}
</script>

Effect picture:
Effect picture

Guess you like

Origin blog.csdn.net/qq_43923146/article/details/109774761