插槽
- 作用:讓父元件可以向子元件指定位置插入html結構,也是一種元件間通信的方式,适用于父元件 ===> 子元件 。
- 分類:預設插槽、具名插槽、作用域插槽
- 使用方式:
- 預設插槽:
父元件中:
<Category>
<div>html結構1</div>
</Category>
子元件中:
<template>
<div>
<!-- 定義插槽 -->
<slot>插槽預設内容...</slot>
</div>
</template>
- 具名插槽:
父元件中:
<Category>
<template slot="center">
<div>html結構1</div>
</template>
<template v-slot:footer>
<div>html結構2</div>
</template>
</Category>
子元件中:
<template>
<div>
<!-- 定義插槽 -->
<slot name="center">插槽預設内容...</slot>
<slot name="footer">插槽預設内容...</slot>
</div>
</template>
- 作用域插槽:
- 了解:資料在元件的自身,但根據資料生成的結構需要元件的使用者來決定。(games資料在Category元件中,但使用資料所周遊出來的結構由App元件決定)
- 具體編碼:
父元件中:
<Category>
<template scope="scopeData">
<!-- 生成的是ul清單 -->
<ul>
<li v-for="g in scopeData.games" :key="g">{{g}}</li>
</ul>
</template>
</Category>
<Category>
<template slot-scope="scopeData">
<!-- 生成的是h4标題 -->
<h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
</template>
</Category>
子元件中:
<template>
<div>
<slot :games="games"></slot>
</div>
</template>
<script>
export default {
name:'Category',
props:['title'],
//資料在子元件自身
data() {
return {
games:['紅色警戒','穿越火線','勁舞團','超級瑪麗']
}
},
}
</script>