Vue脚手架的入门基础(四)—— 关于插槽
1.什么时候用插槽
插槽其实就是一个Vue组件复用时候,某些部分可能需要使用该Vue组件的对象自定义。这样说比较笼统,这边给一个需求就知道了。
下图是三个Vue组件的复用,除了背景Card,标题,卡片中的内容是自定义的,也就是用卡片的外部对象决定的,决定里面放的是图片、视频、列表、还是超链接。
2.插槽的三种使用方式
① 默认插槽
其实就是最基础的插槽调用:
1.定义了一个Category组件
2.在App中调用了这个Category组件
3.在App中标签<Category>
中放入需要的自定义内容(例如图片、视频等)
4.Vue将自定义的内容渲染 Category 组件中的<slot>
标签所在位置
父组件:
<Category title="衣物" :listData="foods">
<img src="https://gitee.com/fuyining/pic-go_img/raw/master/images/16.jpg" alt="">
<a href="https://www.baidu.com">关于我们</a>
</Category>
子组件:
<template>
<div class="category">
<h3>{{title}}分类</h3>
<slot>slot插入出现异常</slot><!-- slot标签内为未渲染时出现的内容 -->
</div>
</template>
② 具名组件
给slot标签命名,可以渲染多个位置。
下方例子中<ul slot="content">
就会把ul整个渲染到组件</Category>
中<slot name="content">
标签的位置,about同理。
父组件:
<Category title="游戏" :listData="games">
<ul slot="content">
<li v-for="(item,index) in games" :key="index">{{item}}</li>
</ul>
<div class="foot" slot="about">
<a href="https://www.baidu.com">更多游戏</a>
<a href="https://www.baidu.com">关于游戏</a>
</div>
</Category>
子组件:
<div class="category">
<h3>{{title}}分类</h3>
<slot name="content">slot插入出现异常</slot>
<slot name="about">slot插入出现异常</slot>
</div>
③ 作用域组件
很多时候调用插槽时候,数据会放在子组件中,那这样做自定义的时候,父组件无法随心所欲的调用子组件数据时候,就可以用作用域组件,简单说就是在子组件中的<slot>
增加props一样的数据(这里是:games=”games“),父组件中只需要在组件中加<template>
,然后通过scope标签属性获得数据内容。
父组件:
<Category title="游戏" >
<template scope="scopeData">
<ul slot="content">
<li v-for="(item,index) in scopeData.games" :key="index">{{item}}</li>
</ul>
</template>
</Category>
子组件:
<div class="category">
<h3>{{title}}分类</h3>
<slot :games="games">slot插入出现异常</slot>
</div>