solt 插槽 内容分发
什么是插槽
- Vue 实现了一套内容分发的 API,将 `` 元素作为承载分发内容的出口。
- 插槽显示的位置却由子组件自身决定,槽写在组件模板的什么位置,父组件传过来的模板将来就显示在什么位置。我们可以理解slot为要占出当前的位置,方便我们插入内容。或者可以这样理解:要去吃饭了,儿子先去占座,然后等他爸爸来了再一起吃。
用法
- 默认插槽,匿名插槽:无name属性,只能用一次
Vue.component("child",{
template:`<div>
111111
<slot></slot>
2222222
<slot></slot>
3333333
<slot></slot>
</div>
`
})
<div id="box">
<child>
<div>联通卡</div>
<div>移动卡</div>
<div>电信卡</div>
</child>
</div>
- 具名插槽:slot属性对应的内容都会和组件中name一一对应
Vue.component("child",{
template:`<div>
111111
<slot name="a"></slot>
2222222
<slot name="b"></slot>
3333333
<slot name="c"></slot>
</div>
`
})
//slot="" 与子组件中name一致
<div id="box">
<child>
<div slot="a">联通卡</div>
<div slot="b">移动卡</div>
<div slot="c">电信卡</div>
</child>
</div>
- 作用域插槽 : 组件上的属性,可以在组件元素内使用
//slot-scope
<child>
<template slot-scope="he">
{{he}}
</template>
<template slot-scope="a">
{{a}}
</template>
<template slot-scope="e">
{{e}}
</template>
</child>
Vue.component('child',{
template:`
<div>
<slot say="hehe"></slot>
<slot a="a"></slot>
<slot 1="1"></slot>
</div>
`
})
//页面显示结果 : { "say": "hehe" } { "a": "a" } { "1": "1" }
新slot v-slot
- 缩写 #名字
- 与之前版本的用法一样,v-solt用在template标签上
<div id="box">
<child>
<template v-slot:a>
<div>联通卡</div>
</template>
<template v-slot:b>
<div>移动卡</div>
</template>
<template #c>
电信卡
</template>
</child>
</div>
Vue.component("child",{
template:`<div>
111111
<slot name="a"></slot>
2222222
<slot name="b"></slot>
3333333
<slot name="c"></slot>
</div>
`
})