插槽是为组件空一个位置可以在需要的时候填上对应需要的标签内容
基本使用
<body>
<div id="app">
<c1></c1>
<c1><a href='www.baidu.com'>我是a</a></c1>
<c1><i>我出来了</i></c1>
<c1><button>点击</button></c1>
</div>
<template id='temp1'>
<div style='border:1px solid black;width:20%'>
<p>我是组件</p>
<slot></slot>
</div>
</template>
<script>
const c1={
template:'#temp1'
};
new Vue({
el: '#app',
components:{
c1
}
})
</script>
</body>
给插槽设置默认值
<body>
<div id="app">
<c1></c1>
<c1><i>slot的默认值span变成了button</i></c1>
<c1></c1>
</div>
<template id='temp1'>
<div style='border:1px solid black;width:20%'>
<slot><span>左边</span></slot>
</div>
</template>
<script>
const c1={
template:'#temp1'
};
new Vue({
el: '#app',
components:{
c1
}
})
</script>
</body>
具名插槽
一个组件里可以有多个插槽,当这些插槽在使用的时候需要修改的时候就要用具名插槽,即给插槽取一个name
当一个模板里有多个slot而在使用组件的时候只需要替换某一个具体的slot时,需要用name来关联
<body>
<div id="app">
<c1>
<button slot='middle'>哈哈</button>
</c1>
</div>
<template id='temp1'>
<div style='border:1px solid black;width:20%'>
<slot name='left'><span>左边</span></slot>
<slot name='middle'><span>中间</span></slot>
<slot name='right'><span>右边</span></slot>
</div>
</template>
<script>
const c1={
template:'#temp1'
};
new Vue({
el: '#app',
components:{
c1
}
})
</script>
</body>