插槽:slot
2025年1月25日大约 2 分钟
插槽:slot
默认插槽
在自定义组件中,如果想要在组件中显示出特定的内容,除了可以自定义Props,还可以把这些内容作为'插入'插槽
假设我们有一个叫Test.vue的组件现在再父组件中使用这个组件
<template>
<Test a="hhh" :b="hhh" @c="fun" /><!--你可以这样子使用这个组件 a,b都是Props, c是自定义事件-->
<Test a="hhh" :b="hhh" @c="fun">
哈哈哈我想在这里写什么都可以<!--在中间写的内容将被插入插槽中-->
</Test>
<Test a="hhh" :b="hhh" @c="fun">
<img arc="imgURL"/><!--在中间写的内容将被插入插槽中-->
</Test>
</template>
<script>
import Test from 'component/Test.vue'
import {ref} from 'vue'
var hhh=ref(100)
function c(){
console.log('test')
}
</script>
在Test.vue组件中
<template>
{{a}}
{{b}}
<slot>'默认内容'</slot>
</template>
slot处将会渲染写在这个组件的其实和结束标签中间的内容,如果没有写的话,则会显示默认内容,默认内容可以为空。
具名插槽(有名字)
上面写的插槽所有东西都会默认插入那个没有名字的默认插槽,但是很多时候我们希望结构更加灵活,比如说在组件标签中写很多段内容,但是我希望每一部分被渲染在不同的地方,这个时候就需要用到具名插槽
<template>
<Test.vue>
<template v-slot:name1>
content1
</template>
<template v-slot:name2>
content2
</template>
<testComponent v-slot:name3/>
<!--这里的内容是要用template标签/或者一个单独的一个component,因为v-slot指令只能用于template和component-->
</Test.vue>
</template>
在对应的Test.vue文件里面,应该要设置三个插槽,命名为name1,name2,name3
<template>
<slot name="name1"></slot>
<slot name="name2"></slot>
<slot name="name3"></slot>
</template>