Vue中插槽的使用(最新版本)

193 阅读1分钟

插槽

形象的说就是在子组件中挖个坑,父组件可以对这个坑进行内容填充

父组件决定了插槽展示内容,子组件决定了插槽所在位置

父组件在子组件标签之间书写html结构,子组件使用slot标签来定义插槽

默认插槽

  • 父组件:father.vue
<template>
  <div>
    <Children>
     <!-- 父组件中可以插入任意html片段 -->
      <p>我是默认插槽</p>
    </Children>  
  </div>
</template>
  • 子组件:son.vue
<template>
  <div>
     <!-- 父组件不书写html片段时,默认展示内容 -->
    <slot>默认展示内容</slot>
  </div>
</template>

具名插槽

如果子组件中存在多个插槽,那么使用匿名插槽就不能区分开来,需要给不同插槽起个名字

  • 父组件:father.vue
<template>
  <div>
    <Children>
      <!-- 对应子组件name为header -->
      <template v-slot:header>
        <p>我是头部具名插槽</p>
      </template>
      <!-- 对应子组件name为content -->
      <template v-slot:content>
        <p>我是中间具名插槽</p>
      </template>
      <!-- 对应子组件name为footer -->
      <template v-slot:footer>
        <p>我是尾部具名插槽</p>
      </template>
    </Children>  
  </div>
</template>
  • 子组件:son.vue
<template>
  <div>
    <!-- 给插槽取个名字 -->
    <slot name="header">我是具名插槽1</slot>
    <slot name="content">我是具名插槽2</slot>
    <slot name="footer">我是具名插槽3</slot>
  </div>
</template>

作用域插槽

如果希望将子组件中的数据传递到父组件的插槽中,就需要使用作用域插槽

  • 父组件:father.vue
<template>
  <div>
    <Children>
      <!-- scope是一个对象,里面接受了子组件插槽传递过来的数据,这里scope命名随意,data,props...啥都行 -->
      <!-- 匿名 -->
      <template v-slot="scope">
        <p>{{scope.content}}</p>
      </template>
      <!-- 也可以使用解构赋值的形式取值 -->
      <template v-slot="{content}">
        <p>{{content}}</p>
      </template>
      
      <!-- 具名 -->
      <template v-slot:header="scope">
        <p>{{scope.title}}</p>
      </template>    
      
    </Children>  
  </div>
</template>
  • 子组件
<template>
  <div>
    <!-- 匿名 -->
    <slot :content="content"></slot>
    
     <!-- 具名 -->
    <slot name="header"
          :title="title"></slot>
  </div>
</template>
<script>
export default {
  data () {
    return {
      content: '我没有名字',
      title: '我有名字',
    }
  }
}
</script>