vue插槽的作用及用法
时间: 2023-11-14 21:06:48 浏览: 28
Vue插槽是Vue组件中的一种特殊语法,用于在父组件中向子组件传递HTML内容。插槽可以让父组件将HTML代码传递给子组件,子组件可以在指定位置渲染这些HTML代码,实现更加灵活的组件复用。
Vue中的插槽分为默认插槽和具名插槽两种,具名插槽可以根据插槽名称传递不同的HTML代码。
用法:
1. 默认插槽
父组件中,使用<slot>标签表示插槽的位置,子组件中,使用props接收父组件传递的HTML代码。
父组件:
```
<template>
<div>
<h2>我是父组件</h2>
<slot></slot>
</div>
</template>
```
子组件:
```
<template>
<div>
<h3>我是子组件</h3>
<div v-html="content"></div>
</div>
</template>
<script>
export default {
props: ['content']
}
</script>
```
2. 具名插槽
父组件中,使用<slot>标签并指定name属性表示具名插槽的位置,子组件中,使用slot标签并指定name属性获取对应的HTML代码。
父组件:
```
<template>
<div>
<h2>我是父组件</h2>
<slot name="header"></slot>
<slot name="content"></slot>
</div>
</template>
```
子组件:
```
<template>
<div>
<h3>我是子组件</h3>
<div class="header">
<slot name="header"></slot>
</div>
<div class="content">
<slot name="content"></slot>
</div>
</div>
</template>
```
使用时,在父组件中传递具名插槽的HTML代码:
```
<template>
<div>
<my-component>
<template slot="header">
<h1>Header</h1>
</template>
<template slot="content">
<p>Content</p>
</template>
</my-component>
</div>
</template>
```