默认插槽
<template>
<div>
<h1>App</h1>
<Son>
<p>传递给默认插槽的内容</p>
</Son>
</div>
</template>
<script>
import Son from '@/components/Son'
export default {
components: {
Son,
}
}
</script>
<template>
<div>
<p>Son</p>
<slot></slot>
</div>
</template>
<script>
export default {
}
</script>
<template>
<div>
<p>Son</p>
<slot></slot>
</div>
</template>
<script>
export default {
}
</script>
- 使用 Son 组件时,给 Son 组件传递的内容会被 Slot 接收到
具名插槽
<template>
<div>
<h1>App</h1>
<Son>
<template v-slot:main>
<h3 >我是main</h3>
</template>
<template v-slot:footer>
<p>我是footer</p>
</template>
</Son>
</div>
</template>
<script>
import Son from '@/components/Son'
export default {
components: {
Son,
}
}
</script>
<template>
<div>
<p>Son</p>
<slot name="main"></slot>
<slot name="footer"></slot>
</div>
</template>
<script>
export default {
}
</script>
- 通过 name 属性给插槽取名字,在使用该组件时,使用 template 并使用 v-slot 指令就可以将内容传递到指定的插槽中, # 号是 v-slot 的简写 (v-slot:main 等价于 #main)
- 一个不带 name 的 <slot> 会自动加上一个 default 的名字
- v-slot 指令需要写在 <template> 上
作用域插槽
<template>
<div>
<h1>App</h1>
<Son>
<template v-slot:main="scope">
{{scope.m}}
<h3 >我是main</h3>
</template>
<template v-slot:footer="{f}">
{{f}}
<p>我是footer</p>
</template>
</Son>
</div>
</template>
<script>
import Son from '@/components/Son'
export default {
components: {
Son,
}
}
</script>
<template>
<div>
<p>Son</p>
<slot name="main" :m="main"></slot>
<slot name="footer" :f="footer"></slot>
</div>
</template>
<script>
export default {
data() {
return {
main: '这是Son组件的data中定义的数据 我需要暴露给外部使用',
footer: 'footer数据也需要暴露给父组件使用'
}
}
}
</script>
- 作用域插槽的思想是,暴露数据给父组件使用
- 子组件定义在两个 slot 具名插槽一个是 main 一个是 footer ,具名插槽 main 中定义了一个属性 m 取值是 main变量,具名插槽 footer中定义了一个属性 f 取值是 footer 变量
- 父组件在使用子组件时,通过 scope 对象可以拿到子组件中暴露的数据
- scope 对象也可以解构,如果不解构名称必须是 scope