Vue 实现了一套内容分发的 API,将 <slot>
元素作为承载分发内容的出口。可以理解为模板中的占位符, 在实例化时用自定义标签元素替代.
本文基于Vue 2.0 最新语法.
slot 的用法大概分为三种:
- 匿名插槽
- 具名插槽
- 作用域插槽
一. 匿名插槽
<template>
<div>
<!-- 匿名插槽 -->
<!-- 一个模板中只能有一个匿名插槽 -->
<span style="display:block;">
匿名插槽
</span>
<!-- 例1, 不带 name 的 slot -->
<slot>
匿名插槽
</slot>
<!-- 例2, 匿名插槽出口会带有隐含的名字“default” -->
<!-- <slot name="default"></slot> -->
</div>
</template>
<script>
export
default {}
</script>
<style>
</style>
<template>
<div>
<slott>
<!-- 匿名插槽 -->
<!-- 例1 -->
<el-button>
确定
</el-button>
<!-- 例2 -->
<!-- <template v-slot:default> <el-button>确定</el-button> </template> -->
</slott>
</div>
</template>
<script>
import slott from '@/components/lesson/pieces/slott'
export
default {
components: {
slott
}
}
</script>
<style>
</style>
二. 具名插槽
<template>
<div>
<!-- 具名插槽 -->
<span style="display:block;">
具名插槽
</span>
<!-- 例1 -->
<slot name="content">
</slot>
<!-- 例2, 缩写 -->
<slot name="short">
</slot>
</div>
</template>
<script>
export
default {}
</script>
<style>
</style>
<template>
<div>
<slott>
<!-- 具名插槽 -->
<!-- 例1 -->
<template v-slot:content>
<el-button type="success">
具名插槽 template
</el-button>
</template>
<!-- 废弃语法, 直接在元素上使用 slot -->
<!-- <el-button slot="content" type="success">具名插槽</el-button> -->
<!-- 例2, 缩写, 默认插槽缩写 #default -->
<template #short>
<el-button type="primary">
具名插槽缩写
</el-button>
</template>
</slott>
</div>
</template>
<script>
import slott from '@/components/lesson/pieces/slott'
export
default {
components: {
slott
}
}
</script>
<style>
</style>
三. 作用域插槽
<template>
<div>
<!-- 作用域插槽 -->
<!-- 作用域插槽用于向父视图传参 -->
<span style="display:block;">
作用域插槽
</span>
<!-- 形式: v-bind:自定义 prop 名=" 数据" -->
<!-- 例1 -->
<slot name="scope" v-bind:data="msg">
后备内容
</slot>
<!-- 例2 -->
<ul>
<slot name="list" v-for="item in arr" v-bind:user="item">
{{ item }}
</slot>
</ul>
<!-- 例3 -->
<!-- 匿名作用域插槽, 一个模板中只能有一个匿名插槽 -->
<!-- <slot name="default" :info="unNamed">匿名作用域插槽</slot> -->
</div>
</template>
<script>
export
default {
data() {
return {
msg: 'message',
arr: ["GOT", "Australia", "NewZealand"],
unNamed: "伏地魔"
}
}
}
</script>
<style>
</style>
<template>
<div>
<slott>
<!-- 作用域插槽 -->
<!-- 形式: v-slot:插槽名="自定义 prop 名" -->
<!-- 例1 -->
<template v-slot:list="slotProps">
{{ slotProps.user + "my love" }}
</template>
<!-- 例2 -->
<template v-slot:scope="scopeProp">
{{ scopeProp.data }}
</template>
<!-- 例3 -->
<template v-slot:default="props">
{{ props.info }}
</template>
<!-- 废弃语法 -->
<!-- <template slot="default" slot-scope="props"> {{ props.info }} </template> -->
</slott>
</div>
</template>
<script>
import slott from '@/components/lesson/pieces/slott'
export
default {
components: {
slott
}
}
</script>
<style>
</style>