Vue2插槽
- Vue2插槽
- 默认插槽
- 子组件代码(`Child.vue`)
- 父组件代码(`Parent.vue`)
- 命名插槽
- 子组件代码(`ChildNamed.vue`)
- 父组件代码(`ParentNamed.vue`)
- 代码解释
Vue2插槽
Vue2插槽
下面为你详细介绍 Vue 2 里默认插槽和命名插槽的使用方法,包含子组件与父组件代码的编写方式。
默认插槽
默认插槽用于在子组件里预留一个位置,方便父组件插入内容。
子组件代码(Child.vue
)
<template>
<div>
<h2>子组件</h2>
<!-- 默认插槽 -->
<slot></slot>
</div>
</template>
<script>
export default {
name: 'Child'
}
</script>
父组件代码(Parent.vue
)
<template>
<div>
<h1>父组件</h1>
<Child>
<!-- 插入到子组件的默认插槽 -->
<p>这是插入到子组件默认插槽的内容</p>
</Child>
</div>
</template>
<script>
import Child from './Child.vue'
export default {
name: 'Parent',
components: {
Child
}
}
</script>
命名插槽
命名插槽允许在子组件中设置多个插槽,父组件可以依据插槽名称往特定插槽插入内容。
子组件代码(ChildNamed.vue
)
<template>
<div>
<h2>带命名插槽的子组件</h2>
<!-- 命名插槽 -->
<slot name="header"></slot>
<p>子组件的主体内容</p>
<slot name="footer"></slot>
</div>
</template>
<script>
export default {
name: 'ChildNamed'
}
</script>
父组件代码(ParentNamed.vue
)
<template>
<div>
<h1>使用命名插槽的父组件</h1>
<ChildNamed>
<!-- 插入到子组件的 header 插槽 -->
<template #header>
<h3>这是插入到子组件 header 插槽的内容</h3>
</template>
<!-- 插入到子组件的 footer 插槽 -->
<template #footer>
<p>这是插入到子组件 footer 插槽的内容</p>
</template>
</ChildNamed>
</div>
</template>
<script>
import ChildNamed from './ChildNamed.vue'
export default {
name: 'ParentNamed',
components: {
ChildNamed
}
}
</script>
代码解释
- 默认插槽:子组件里使用
<slot></slot>
定义默认插槽,父组件在使用子组件时,直接在子组件标签内插入内容,这些内容就会显示在默认插槽的位置。 - 命名插槽:子组件通过
name
属性定义命名插槽,像<slot name="header"></slot>
。父组件借助<template #插槽名>
语法把内容插入到对应的命名插槽。
这些示例代码能够让你清晰地理解 Vue 2 中默认插槽和命名插槽的用法。你可以依据实际需求对代码进行调整和扩展。