一、插槽的定义
vue实现了一套内容分发的Api,将<slot>元素作为承载内容分发
二、插槽的注意事项
父组件模板的内容只能访问父组件的作用域,子组件的模板只能访问子组件的作用域。
也就是说插槽的内容可以访问父组件的数据作用域,因为插槽内容本身就是在父组件的模板中定义的,插槽内容是无法访问子组件中的数据,vue模板中的表达式只能访问其定义时在所处的作用域,这个和js的词法作用域规则是一样的。
三、普通插槽
// 父组件
import chacao from "./chacao.vue"
components:{ chacao }<chacao>hahaja<span>fffff</span>
</chacao>// 子组件
<div><slot></slot> // 所有内容将会显示到这
</div>
四、后备内容
有时为一个插槽设置具体的后备(也就是默认)内容是很有用的,它只会在没有被提供内容的时候被我渲染
// 父组件:提供了内容,子组件显示save
<submit-button>save
</submit-button>// 父组件: 无内容,子组件显示submit
<submit-button>
</submit-button>// 子组件
<button type="submit"><slot>submit</slot>
</button>
五、具名插槽
父组件的三种写法
import chacao from "./chacao"
components:{chacao}// 第一种使用: v-slot + template
<chacao><template v-slot:one>one</template><template v-slot:two>two</template><div> three </div>
</chacao>// 第二种使用: # + template, v-slot: 等同于#,是一种简写方式
<chacao><template #one>one</template><template #two>two</template><div> three </div>
</chacao>// 第三种使用: slot(没有v-) +具体标签(不能是template)
<chacao><div slot="one">one</div><div slot="two">two</div><div> three </div>
</chacao>
子组件
<template><div><slot name="one"></slot> // one<slot name="two"></slot> // two<slot></slot> // three</div>
</template>
六、作用域插槽
某些场景下,插槽的内容想要同时使用父组件和子组件内的数据,要做到这一点,我们需要来让子组件在渲染的时候将一部分的数据提供给插槽
(1)只有默认插槽
// 父组件,只有默认插槽,也可以在组件标签上使用解构赋值v-slot="{text,wyz}"
<chacao v-slot="slotProps"><div>{{slotProps.text}}-{{slotProps.wyz}}</div>
</chacao>// 子组件
<slot text="a" wyz="wyz"></slot>
(2)只有具名插槽
// 父组件
<chacao>// 普通使用<template #one="proplot"> {{proplot.text}}</template>// 解构赋值<template #two="{wyz}"> {{wyz}}</template>
</chacao>// 子组件
<slot name="one" text="wyz"></slot>
<slot name="two" wyz="wyz"></slot>
(3)同时具有默认和具名插槽
// 父组件
<chacao><template #one="{text}">{{text}}</template><template #two="{wyz}">{{wyz}}</template><template #default="{defaultName}">{{defaultName}}</template>
</chacao>// 子组件
<slot name="one" text="wyz"></slot>
<slot name="two" wyz="wyz"></slot>
<slot defaultName="66-88"></slot>