Vue中的slot标签——插槽
1.基本概念
slot插槽是Vue中的一个重要功能,它允许我们向组件传递模板内容。父组件可以在使用子组件时,在子组件的标签内传入内容,这些内容会被渲染到子组件内部的slot标签内。
2.插槽类型
2.1 默认插槽
没有名字的插槽,每个组件只能有一个。
<template><div><slot></slot></div>
</template>
2.2 具名插槽
带有name属性的插槽,可以使用多个。使用template标签和v-slot指令来指定内容应该插入到那个具名插槽中,具名插槽默认情况下只解决“插槽往哪放”的问题。
/* 子组件定义的具名插槽 */
<div class="container"><header><slot name="header"></slot></header><main><slot></slot></main><footer><slot name="footer"></slot></footer>
</div>/* 父组件使用的具名插槽 */
<BaseLayout><template v-slot:header><h1>页面标题</h1></template><template v-slot:default><p>主要内容</p></template><template v-slot:footer><p>页脚内容</p></template>
</BaseLayout>
2.3 作用域插槽
能够接收子组件传递的数据的插槽。
/* 子组件传递数据 */
<slot :text="greetingMessage" :count="1"></slot>/* 父组件接收数据 */
<MyComponent v-slot="slotProps">{{ slotProps.text }} {{ slotProps.count }}
</MyComponent>
3. 插槽的特点
- 插槽内容可以访问到父组件的数据作用域
- 插槽的内容无法访问子组件的数据作用域(可以使用作用域插槽解决)
代码示例:
/* 父组件 */
<template><Child><!-- 插槽内容写在父组件中,作用域是父组件 --><p>{{ parentMessage }}</p></Child>
</template><script setup>
import { ref } from 'vue'
import Child from './Child.vue'const parentMessage = ref('Hello from parent')
</script>/* 子组件 */
<template><div><slot></slot></div>
</template><script setup>
const childMessage = ref('Hello from child') // 插槽内容访问不到这个
</script>
4.扩展:
v-slot
是统一语法糖,用来声明式地“接收”子组件通过 <slot>
暴露出来的数据。
它把原来分散的 slot=""
和 slot-scope=""
合并成一条指令。
总结:v-slot = “在父组件里给子组件的插槽起个名字,同时把子组件抛出来的数据接收”,并且具名插槽 + 作用域插槽可以实现传值和定位。
/* 子组件,具名插槽 + 作用域插槽 */
<slot name="header" :title="pageTitle"/>/* 父组件 */
<template #header="{title}">这里是标题:{{ title }}
</template>