vue插槽的使用~

360 阅读1分钟

基本使用

//MyButton组件
<button class="[btnStyle]">
    <slot>按钮</slot> // 默认插槽内容
</button>
export default {
    name: 'MyButton',
    props: ['btnStyle']
}
//使用
<MyButton btnStyle="样式名称">
    //可插入文本 组件等...
</MyButton>

具名插槽

//MyButton组件
<button class="[btnStyle]">
    <slot name="icon"></slot>
</button>
export default {
    name: 'MyButton',
    props: ['btnStyle']
}
//使用
<MyButton btnStyle="样式名称">
    //可插入文本 组件等...
    <template v-slot:icon>
        <i class="icon-class"></i>
    </template>
</MyButton>

作用域插槽

//MyButton组件
<button class="[btnStyle]">
    <slot name="icon" :btnInfo="btnInfo"></slot>
</button>
export default {
    name: 'MyButton',
    props: ['btnStyle'],
    data () {
        return {
            btnInfo: {
                url: 'www.baidu.com'
            }
        }
    }
}
//使用
<MyButton btnStyle="样式名称">
    //可插入文本 组件等...  
    <template v-slot:icon="btnInfo">
        <i class="icon-class"></i>
        {{btnInfo.url}} //btnInfo可以拿到MyButton传出来的值
    </template>
</MyButton>