VueJS slot插槽

参考教程

插槽的使用

最简单的使用 //父组件可以再slot 中可以放置多个元素,会一起替代掉原有的默认,都会显示出来

子组件 cart 组件

 <div>
    <h2>插槽组件</h2>
    <slot></slot>
 </div>

父组件

<cart>
  <button>按钮
</cart>

此时 button就会替代slot

默认插槽

子组件 cart 组件,button默认插槽显示

 <div>
    <h2>插槽组件</h2>
    <slot><button>按钮</button></slot>
 </div>

父组件

<cart>
  
</cart>

此时 页面会默认显示button

简单使用

子组件 cart 组件

 <div>
    <h2>插槽组件</h2>
    <slot>阿萨德</slot> 
 </div>

父组件

<cart id="'a'" name="'b'">
  <div>父组件中的插槽</div>
</cart>

此时显示的内容是 父组件中的插槽 。如果没有 slot,则不会显示父组件的DIV内容
总结:如果子组件没有使用插槽,父组件如果需要往子组件中填充模板或者html, 是没法做到的

有name的插槽 具名插槽

如果子组件有name,没有空的slot ,而父组件不指定name,则template 里面的内容不显示。
所以子组件有name,父组件一定要通过 v-slot绑定name名
子组件

<template>
   <div>
    <h2>插槽组件</h2>
    <slot name="slot1" ></slot>
    <slot>子组件的默认slot2</slot>
    </div>
</template>

父组件

slot="slot1" 这样子也可以。
 <cart id="'a'" name="'b'">
      <template v-slot:slot1>  
        <h1>我是子组件</h1>
      </template>

       <template >
        <h1>我是子组件2</h1>
      </template>
</cart>
原文地址:https://www.cnblogs.com/Alex-Mercer/p/12506833.html