当A组件要使用多次B组件的结构,但有些B组件的结构需要单独写的时候,使用组件插槽。
匿名插槽的基本使用
// A组件
<B>哈哈哈</B>
<B>嘿嘿嘿</B>
import B from 'B'
components:{B}
//B组件
<template>
<div>
你好
<slot>hello world</slot>
</div>
</template>
匿名插槽只适合在有一处不确定要写什么的时候使用。
上面的案例在A组件里就会显示:
你好 哈哈哈
你好 嘿嘿嘿
B组件定义了slot标签,A组件写在<B>标签里的内容就会渲染到B组件的slot标签处,
同时B组件在slot标签里设置了默认显示内容,如果A组件只写了<B></B>,没往里面写任何东西的话,显示的就是:hello world。
具名插槽
// A组件
<B>
<template v-slot:A1>第一个插槽</template>
<template #A2>第二个插槽</template>
</B>
import B from 'B'
components:{B}
//B组件
<template>
<div>
<slot name='A1'></slot>
<br />
你好
<br />
<slot name='A2'>hello world</slot>
</div>
</template>
具名插槽适合在有多处不确定写什么的时候使用。
上面的案例在A组件里会显示:
第一个插槽
你好
第二个插槽
上面A组件里写的 v-slot:A1 实际上等效于 #A1 , #是v-slot的简写。
作用域插槽
//A组件
<B>
<template v-slot='A'>数据{{A.B1}}</template>
</B>
import B from 'B'
components:{B}
//B组件
<template>
<div>
<slot :B1='b'></slot>
你好
</div>
</template>
data(){
return{b:'hello world'}
}
作用域插槽适合A组件需要用B组件的数据来进行渲染时使用。
上面的案例在A组件里会显示:
数据 hello world 你好
格式为:
A组件:<B><template v-slot='自定义数据名A'>{{自定义数据名A.子组件自定义名B}}</template></B>
B组件:<slot :子组件自定义名B='数据名'></slot>
具名插槽+作用域插槽
//A组件
<B>
<template v-slot:c1='A'>{{A.B1}}</template>
<template #c2='A2'>{{A2.B2}}{{A2.B3}}</template>
</B>
import B from 'B'
components:{B}
//B组件
<template>
<div>
<slot name='c1' :B1='b'></slot>
<br />
<slot name='c2' :B2='b2' :B3='b3'></slot>
</div>
</template>
data(){
return{b:'hello world',b2:'你好 世界',b3:'哈哈哈哈'}
}
上面的案例在A组件里显示为:
hello world
你好 世界哈哈哈哈
格式为:
A组件:<B>
<template v-slot:B组件自定义插槽名1='自定义数据名A'>{{自定义数据名A.子组件自定义名B1}}</template>
<template #B组件自定义插槽名2='自定义数据名A2'>{{自定义数据名A2.子组件自定义名B2}}
{{自定义数据名A2.子组件自定义名B3}}</template>
</B>
B组件:
<slot name='B组件自定义插槽名1' :子组件自定义名B1='数据名1'></slot>
<slot name='B组件自定义插槽名2' :子组件自定义名B2='数据名2' :子组件自定义名B3='数据名3'></slot>