v-slot可以将components标签里面的文字内容替换到指定的位置。
用文字叙述不太清楚,还是用特定的场景来描述吧。
比如你有一个button组件,你想让他根据不同的需求显示不同的文字,使他的可复用性更高:
<body>
<!-- v-slot 插槽 -->
<!-- 简写 # -->
<div id="app">
<!-- 想根据组件标签里的内容来显示我的button -->
<my-button type="success">成功按钮</my-button>
</div>
<script>
const vm = new Vue({
el: '#app',
components:{
myButton:{
props: ['type'],
//使用slot标签,文字会替换到slot标签的位置
template:`<button class="my-button" :class="type">
<slot></slot>
</button>`
}
}
});
</script>
</body>
效果:
slot标签还可以有一个name属性,可以在template标签上用v-slot:name指令将内容替换到固定name值的slot标签上,
==v-slot可简写为 一个井号 # ==
<body>
<!-- v-slot 插槽 -->
<!-- 简写 # -->
<div id="app">
<my-button type="success">成功按钮
<template v-slot:right>
success
</template>
</my-button>
</div>
<script>
const vm = new Vue({
el: '#app',
components:{
myButton:{
props: ['type'],
template:`<button class="my-button" :class="type">
<slot></slot>
-------------
<slot name="right"></slot>
</button>`
}
}
});
</script>
</body>
效果: