vue中slot插槽的使用
文章目录
为什么要用slot?
现有一个写好样式的布局组件,我们仅需要在特定的位置中填充内容,就可以将需要的效果显示出来。但是这里我们不能直接将内容填充进去,因为那样这个组价就没用什么意义了,它只是一个布局组件。
假如我们现在有一个布局组件slotSun.vue,里面写满了各种样式,我们只需要将内容传递进去就可以看到效果。
<template>
<div class="all">
<div>
接受内容的位置
</div>
</div>
</template>
<script>
export default {
name:'slotSun'
}
</script>
<style>
`/* 假设这里有超多样式 */`
</style>
我们将该组件引入我们的vue项目中
<template>
<div>
<slot-sun></slot-sun>
</div>
</template>
<script>
import slotSun from '@/components/slotSun.vue'
export default {
components:{
slotSun
}
}
</script>
<style>
</style>
根据我们平时的html节点思想,我们如果想将内容添加进slot组件中,首先会想到的是这样写:
<template>
<div>
<slot-sun>
<span>this is content</span>
</slot-sun>
</div>
</template>
这时候我们打开浏览器看一下就会发现页面中只有布局组件,<span>this is content</span>并没有显示,因为这里的<span>和<slot-sun>并不是普通的父子节点关系,这时候我们就需要用到slot。
slot的几种使用方法
1. 插槽的直接使用
我们可以在组件中需要传入内容的地方直接声明slot
布局组件:
<template>
<div class="all">
<div>
<!-- 需要传入内容的地方 -->
<slot></slot>
</div>
</div>
</template>
父组件
<template>
<div>
<slot-sun>
<span>this is content</span>
</slot-sun>
</div>
</template>
这时候我们就可以看到span中的内容显示出来了。
2. 具名插槽的使用
如果组件中需要传入多个内容放在不同的位置的时候,我们可以使用具名插槽来分别插入
布局组件:
<template>
<div class="all">
<div>
<!-- 需要传入内容的地方 -->
<slot name="header"></slot>
</div>
<div>
<!-- 需要传入内容的地方 -->
<slot name="body"></slot>
</div>
</div>
</template>
父组件:
<template>
<div>
<slot-sun>
<span slot="header">this is header</span>
<span slot="body">this is body</span>
</slot-sun>
</div>
</template>
3. 插槽作用域的使用
我们有时候会遇到这种情况,在父组件中需要调用子组件里面的值,这个时候我们可以这样来引用:
布局组件:
<template>
<div class="all">
<div>
<!-- 需要传入内容的地方 -->
<slot name="wang" age="20"></slot>
</div>
</div>
</template>
父组件:
<template>
<div>
<slot-sun>
<span slot-scope="props">{{props.name}}:{{props.age}}</span>
</slot-sun>
</div>
</template>
这里我们给span标签添加上slot-scope="props"之后,props就相当于span标签里面特有的一个对象,里面存储着子组件插槽中传递来的值,结构为:
{
name:'wang',
age:'20'
}
这样就可以在span标签直接进行调用啦。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论