普通用法:
1. 新建compA.vue组件,内容为:
<template>
<div>
<div class="head">
<slot name="head">具名插槽-头</slot>
</div>
<slot>占位内容</slot>
<div class="foot">
<slot name="foot">具名插槽-尾</slot>
</div>
</div>
</template>
2.在test.vue文件中导入并使用:
<template>
<div>
<compA></compA>
<compA>只替换正文内容</compA>
<compA>
<template slot="head">真正要的头部</template>
其他正文内容...
<template slot="foot">真正要的尾部</template>
</compA>
</div>
</template>
<script>
import compA from "./compA";
export default {
components:{compA},
}
</script>
<style>
</style>
3.页面展示结果:
<slot name="head"> : slot标签设置插槽,name属性设置插槽名称
<template slot="head"> : slot属性设置使用的插槽,vue2.6以后的版本会用v-slot来替代
高级用法:(使用的是vue版本至少要是2.6.0)
1.组件设置两个插槽,一个默认的<slot></slot>,一个<slot name="option" :item="item"></slot>并且绑定了参数item
<el-select :value.sync="value" :placeholder="placeholder" :clearable="clearable" :disabled="disabled" @change="change">
<slot></slot>
<el-option :label="item.name" :value="item.id" v-for="item in datas" :key="item.id">
<slot name="option" :item="item"></slot>
</el-option>
</el-select>
2.<el-option label="123" value="1"></el-option>是默认插槽的节点,
<template v-slot:option='scope'>是绑定了具名插槽option的节点,并且通过v-slot接收到参数scope,
<SelectRemote v-model="form.financeDivideId" @change="d=>form.financeDivideId=d" url="/financeDivide/all" placeholder="请选择资金账号" :required="true">
<el-option label="123" value="1"></el-option>
<template v-slot:option='scope'>
<span style="float: left">{{ scope.item.id }}</span>
<span style="float: right;font-size: 13px">名称:{{ scope.item.name }}</span>
</template>
</SelectRemote>
也可以通过结构赋值 v-slot:option='{item}'直接拿到绑定的参数,如下:
<SelectRemote v-model="form.financeDivideId" @change="d=>form.financeDivideId=d" url="/financeDivide/all" placeholder="请选择资金账号" :required="true">
<el-option label="123" value="1"></el-option>
<template v-slot:option='{item}'>
<span style="float: left">{{ item.id }}</span>
<span style="float: right;font-size: 13px">名称:{{ item.name }}</span>
</template>
</SelectRemote>
3.v-slot的省略写法 # ,和解构赋值
<div class="container">
<header>
<slot name="header" :attr1="data1"></slot>
</header>
<main>
<slot :attr2="data2"></slot>
</main>
<footer>
<slot name="footer" :attr3="data3"></slot>
</footer>
</div>
<layout>
<!-- 正常传参 -->
<template #header="props">
<h1>{{props.attr1}}</h1>
</template>
<!-- 解构赋值 -->
<template #default="{attr2}">
<p>{{attr2}}</p>
</template>
<!-- 解构赋值并重命名 -->
<template #footer="{attr3:myProp}">
<p>{{myProp}}</p>
</template>
</layout>
<slot>标签的name属性给插槽设置名称,通过(v-bild或者:)绑定的自定义属性用于传参
v-slot 只能添加在 <template> 上, v-slot可以使用缩写形式 # ,比如v-slot:header="xxx" 等价于 #header="xxx" ,使用缩写必须要有名称, 默认的使用 #default
参考:官方文档
老版本传参的参考:官方文档