vue 插槽的使用:
插槽定义:
是 vue 一种内容分发机制, 将 slot 元素作为 承载分发内容的出口(Vue 实现的一套内容分发的 API);
插槽分类:
-
默认(匿名)插槽
-
具名插槽
-
作用域插槽
插槽使用:
默认(匿名)插槽:
<slot></slot>
或者是<slot name="default"></slot>
子组件中有一个没有属性的 slot 标签的时候,父组件调用时,将整个内容片段插到 slot 所在的 dom 位置,替换掉 slot 标签本身;如果没有 slot 标签,父组件调用时,内部的代码片段将会被丢弃
<!-- 子组件中的代码 -->
components:{
child:{
template:`
<div>
<div>今天的天气是:</div>
<slot></slot>
</div>
`
}
}
<!-- 父组件的代码 -->
<div id="app">
<child>
<span>大到暴雨 七级大风 温度20-38℃</span>
</child>
</div>
具名插槽:
给插槽取名,通过 template 标签将需要分发的内容进行包裹,并且通过 v-slot:插槽名,实现定向分发;
如果一个组件中需要使用多个插槽的时候,那么就需要使用具名插槽。
<!-- 子组件定义插槽的名字 -->
Vue.component("child",{
template:`
<div>
<div>今天的天气是:</div>
<slot name="weather"></slot>
<slot name="temperature"></slot>
</div>
`
})
<!-- 父组件调用子组件的时候,相对应的位置通过插槽名进行分配内容 -->
<div id="app">
<child>
<span slot='weather'>{{weather}}</span>
<span slot="temperature">{{temperature}}</span>
</child>
</div>
作用域插槽:
主要是为了让插槽内容能够访问到子组件中才有的数据;
分发内容时使用子组件中的数据 ,此时使用作用域插槽 在定义 slot
的同时,添加自定义属性,用于传参<slot :weather="weather"></slot>
添加的所有自定义属性,都会以属性的方式添加到新的对象中,对象存在 template
中 v-slot:weather(插槽名)="{weather}"
属性里可以通过等号接收
默认插槽传递数据,则使用v-slot:default="{属性名,属性名...}"
<!-- 子组件中的代码,自定义weather属性,指定了插槽的名称 -->
Vue.component("child", {
template: `
<div>
<div>今天的天气情况:</div>
<slot :weather="weather" name="weather">
<div v-for="(item,index) in weather" :key="index">{{item}}</div>
</slot>
</div>
`,
data() {
return {
weather:["12℃ 阴转大雨","28℃ 晴","26℃ 阴转多云"]
}
}
})
<!-- 父组件中,通过v-slot:插槽名称="{属性名}" -->
<div id="app">
<child v-slot:weather="{weather}" >
<div v-for="(item,index) in weather" :key="index">{{item}}</div>
</child>
</div>