Vue插槽slot

98 阅读1分钟
  • slot的作用:在子组件内使用特殊的<slot>元素就可以为这个子组件开启一个slot(插槽),在父组件模板里,插入在子组件标签内的所有内容将替代子组件的<slot> 标签及它的内容。
  • 理解:就是在子组件内部用 slot 标签占位,当在父组件中使用子组件的时候,我们可以在子组件中插入内容,而这些插入的内容则会替换 slot 标签的位置
// 父组件中的代码
<template>
  <div class="hello">
    <MyComponents>
      <p>我插入了内容</p> // 在组件中插入了p标签
    </MyComponents>
  </div>
</template>

// 子组件MyComponents中的代码
<template>
  <div>
    <p>这是子组件</p>
    <slot> // 当父组件中,有替代的内容时就把slot替换,没有的话,就默认使用slot中的内容替换slot
         <p>父组件中没有插入内容,我就是默认内容</p>
    </slot>
  </div>
</template>
具名插槽:
// 父组件
<template>
  <div class="hello">
    <p>总数:{{total}}</p>
    <MyComponents>
     // 这个p会替换子组件中的name属性为first的slot标签
      <p slot="first">匹配第一个插槽的内容</p>
     // 这个p会替换子组件中的没有name属性的slot标签,有几个替换几个
      <p>我插入了内容</p>
     // 这个p会替换子组件中name属性为last的slot标签
      <p slot="last">匹配最后一个插槽</p>
    </MyComponents>
  </div>
</template>

// 子组件MyComponents
<template>
  <div>
    <button @click="handleClick">+1</button>
    <slot name="first"></slot>
    <slot>父组件中没有插入内容,我就是默认内容</slot>
    <slot></slot>
    <slot name="last"></slot>
  </div>
</template>