vue 插槽的种类

547 阅读3分钟

默认插槽

默认插槽:<slot></slot>
在子组件中定义一个默认插槽:
子组件中
<div class="child-page">
        <h1>子页面</h1>
        <slot></slot>  //  替换为 <p>hello,world!</p>
    </div>
父组件中
<my-component>
    <p>hello,world!</p>
  </my-component>
//  渲染结果
    <div class="child-page">
        <h1>子页面</h1>
        <p>hello,world!</p>
    </div>

具名插槽

就是带名字的插槽,需要在组件内部预留多个插槽位置,就需要为插槽定义名字,指定插入的位置。
父组件中 
<my-component>
    <template v-slot:header>
     <p>头部</p>  
    </template>
    <template v-slot:footer>
     <p>底部</p>
    </template>
    <p>主体部分</p>
  </my-component>
    子组件中
    <div class="child-page">
        <h1>子页面</h1>
        <slot name="header"></slot>
        <slot></slot>  //  等价于 <slot name="default"></slot>
        <slot name="footer"></slot>
    </div>
//  渲染结果
    <div class="child-page">
        <h1>子页面</h1>
        <p>头部</p>
        <p>主体部分</p>
        <p>底部</p>
    </div>

vue >=2.6.0版本,使用v-slot替代slot 和 slot-scope。

  • 具名插槽的内容必须使用模板包裹
  • 不指定名字的模板插入匿名插槽中,推荐使用具名插槽,方便代码追踪且直观清楚
  • 匿名插槽具有隐藏的名字"default"
具名插槽的缩写和动态插槽名
具名插槽的缩写
<my-component>
    <template #header>
      <p>头部</p>  
    </template>
    <template #footer>
      <p>脚部</p>
    </template>
    <template #body>
      <p>身体</p>
    </template>
  </my-component>
动态插槽名
<my-component>
    <template #[header]>
      <p>头部</p>  
    </template>
    <template #footer>
      <p>脚部</p>
    </template>
    <template #body>
      <p>身体</p>
    </template>
  </my-component>
  <script>
  export default{
    data() {
    return {
      headerPart: 'header'
    }
  }
  }
    
  </script>

作用域插槽

作用域插槽可以接收子组件传递的值,并根据不同的值显示不同的内容。如根据用户根据返回的值控制样式信息。

插槽父传子 接收子

//  组件(父)
  <my-component
    :data="data"
  >
    <template #header='scope'>
      <p>头部 {{scope.header}}</p>  
    </template>
    <template #footer>
      <p>尾部{{scope.body}}</p>
    </template>
    <template #body>
      <p>主体部分{{scope.footer}}</p>
    </template>
  </my-component>
  <script>
  export default{
      data(){
          return {
              data:{
                  header:'头部1',
                  body:'主体部分1',
                  footer:'尾部1',
              }
          }
      }
  }
  </script>

子组件props接收值再传到父组件

//  组件内部(子)
    <div class="child-page">
        <slot name="header" :header="data.header"></slot>
        <slot name="body" :body="data.body"></slot>
        <slot name="footer" :footer="data.footer"></slot>
    </div>
    <script>
    export default{
        props: {
        data: {
            type: Object,
            default: function () {
        return { header: 'hello',body: 'hello',footer: 'hello' }
      }
        }
    }
    }
    </script>

父组件传参给子组件,props接收后,插槽slot再通过绑定属性传递参数返回给父组件,不管是模板代码还是数据,控制权完全掌握在父组件手里。