slot简介
插槽slot,就是子组件提供给父组件使用的一个占位符<slot></slot>
插槽的基本使用
// 子组件 Son
<template>
<h1>
<slot></slot>
</h1>
</template>
// 父组件
<Son>父组件展示的内容</Son>
// 页面显示 : <h1>父组件展示的内容</h1>
后备内容(默认值)
当父组件使用子组件没有提供内容的时候被渲染
// 子组件 Son
<template>
<h1>
<slot>子组件默认展示内容</slot>
</h1>
</template>
// 父组件
<Son></Son>
// 页面显示 : <h1>子组件默认展示内容</h1>
具名插槽
具名插槽就是给插槽取个名字。一个子组件可以放多个插槽,而且可以放在不同的地方,而父组件填充内容时,可以根据这个名字把内容填充到对应插槽中。
// 子组件 Son
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot> // 默认插槽,没有指定插槽名字时内容将默认展示在此处
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
// 父组件
<div>
<Son>
<template v-slot:header>
<h1>头部区域</h1>
</template>
<template v-slot:default>
<h1>默认插槽内容区</h1>
</template>
<template v-slot:footer>
<h1>尾部区域</h1>
</template>
</Son>
</div>
作用域插槽(插槽传值)
子组件给父组件传递数据
// Son 子组件
<template>
<div>
<slot :user="user"></slot>
</div>
</template>
<script>
export default {
data(){
return{
user:{
name:'小明',
age:18
}
}
}
}
</script>
// 父组件
<template>
<div>
<Son>
//<template v-slot:default="sonProps">
//{{ sonProps.user.name }}
//<template>
// 可以进行解构
<template v-slot:default="{{user}}">
{{ user.name }}
<template>
</Son>
</div>
</template>