1.单个插槽、匿名插槽
在子组件中,可以这样写
<a
v-bind:href="url"
class="nav-link"
>
<slot></slot>
</a>
然后在父组件中可以像如下使用子组件:
<navigation-link url="/profile">
Your Profile
</navigation-link>
当组件被渲染时,slot
会被替换为 Your Profile
<a
v-bind:href="url"
class="nav-link"
>
Your Profile
</a>
- 具名插槽
需要多个插槽时,我们可以利用 slot
的一个特殊特性,name
来定义具名插槽,在向具名插槽提供内容的时候,我们可以在一个 <template>
元素上使用 v-slot
指令,并以 v-slot
的参数的形式提供其名称,(v-slot
可以缩写为 # ) :
子组件中这样定义:
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
父组件中使用子组件,节点上使用 slot
特性:
<base-layout>
<h1 v-slot:header>Here might be a page title</h1>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<p v-slot:footer>Here's some contact info</p>
</base-layout>
也可以在外层套用一个 templete
节点,在节点上使用 slot
属性。
渲染出来的 HTML
都将会是:
<div class="container">
<header>
<h1>Here might be a page title</h1>
</header>
<main>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</main>
<footer>
<p>Here's some contact info</p>
</footer>
</div>
- 作用域插槽---带数据的插槽
单个插槽和具名插槽都不绑定数据,所以父组件既要提供样式又要提供数据,作用域插槽是子组件提供数据,父组件只提供样式
子组件中:
<template>
<div class="child">
<h3>这里是子组件</h3>
// 作用域插槽
<slot :data="data"></slot>
</div>
</template>
export default {
data: function(){
return {
data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
}
}
}
父组件中:
<template>
<div class="father">
<h3>这里是父组件</h3>
<!--第一次使用:用flex展示数据-->
<child>
<template slot-scope="user">
<div class="tmpl">
<span v-for="item in user.data">{{item}}</span>
</div>
</template>
</child>
<!--第二次使用:用列表展示数据-->
<child>
<template slot-scope="user">
<ul>
<li v-for="item in user.data">{{item}}</li>
</ul>
</template>
</child>
<!--第三次使用:直接显示数据-->
<child>
<template slot-scope="user">
{{user.data}}
</template>
</child>
<!--第四次使用:不使用其提供的数据, 作用域插槽退变成匿名插槽-->
<child>
我就是模板
</child>
</div>
</template>
网友评论