如电脑的usb插槽可以插键盘等类似,组件的插槽是为了让封装的组件更加具有扩展性,让使用者可以决定组建内部的一些内容到底展示什么
例子:
<body>
<div id="app">
<cpn><button>按钮</button></cpn> //中间添加了button,则显示的时一个按钮
<cpn></cpn> //中间不添加任何东西,则slot显示的默认值11
</div>
<template id="cpn1">
<div>
<h2>试试</h2>
<slot>11</slot> //设置的插槽,11为设置的默认值。
</div>
</template>
<script>
const vue =new Vue({
el:'#app',
data:{
message:'aaa'
},
components:{
cpn:{ template:'#cpn1' }
}
})
</script>
</body>
当插槽中所用的次数较多,如button按钮,则可以如<slot><button></button></slot>,此为设置的默认,即当调用组建时没有设置如<cpn></cpn>,则会显示默认设置的按钮.想要改变插槽的东西则在调用时候在中间添加如<cpn><button>按钮</button></cpn>,在中间添加自己想要的内容。
二、具名插槽
当有多个插槽时,我们想要替换其中的一个,就需要给插槽起名,这样在调用时候对应相对的名称就可以修改对应的插槽内容
例子
<body>
<div id="app">
<cpn><button>按钮</button></cpn> //中间添加了button,则显示的时一个按钮
<cpn><p slot="b">4</p></cpn> //在<p>中对应slot名称,并修改第二个slot值为4
</div>
<template id="cpn1">
<div>
<h2>试试</h2>
<slot name="a">1</slot>
<slot name="b">2</slot>
<slot name="c">3</slot> //设置的插槽
</div>
</template>
<script>
const vue =new Vue({
el:'#app',
data:{
message:'aaa'
},
components:{
cpn:{ template:'#cpn1' }
}
})
</script>
</body>
作用域插槽:
父组建替换插槽的标签,但是内容却是子组件提供的
例子:
<body>
<div id="app">
<cpn></cpn>
<template slot-scope='solt'> //用slot-scope=‘slot’来获取子组件的message
<span v-for='item in slot.abc'>//通过slot.abc来遍历message,message名称被abc代替
</template>
</div>
<template id="cpn1">
<div>
<h2>试试</h2>
<slot :abc=‘message’></slot> //给插槽设置一个名称abc来获取message
</div>
</template>
<script>
const vue =new Vue({
el:'#app',
data:{
message:'aaa'
},
components:{
date(){
return{
message:['c','java','php'] //子组件定义的数组需要在父组件调用的组件里显示
}
}
cpn:{ template:'#cpn1' }
}
})
</script>
</body>