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> 模板
<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> 使用
二. 具名插槽
<template> <div> <!-- 具名插槽 --> <span style="display:block;">具名插槽</span> <!-- 例1 --> <slot name="content"></slot> <!-- 例2, 縮寫 --> <slot name="short"></slot> </div></template><script>export default { }</script> 模板
<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> 使用
三. 作用域插槽
<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> 模板
<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> 使用