【Vue2.0学习】—插槽(六十四)

  • 作用:让父组件可以向子组件指定的位置插入html结构,也是一种组件间通信的方式,适用于 父组件=》子组件
  • 分类:默认插槽、具名插槽、作用域插槽

默认插槽

使用方式:

【Vue2.0学习】—插槽(六十四)_插槽

具名插槽

【Vue2.0学习】—插槽(六十四)_作用域_02

作用域插槽

理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由APP组件决定)

【Vue2.0学习】—插槽(六十四)_1024程序员节_03


【Vue2.0学习】—插槽(六十四)_作用域_04


作用域插槽案例:

App.vue

<template>
<div class="app">


<Category title="游戏">
<template scope="play">
<ul>
<li v-for="(g,index) in play.games" :key="index">{{g}}</li>
</ul>
</template>
</Category>

<Category title="游戏">
<template scope="{games}">
<ol>
<li style="color:red" v-for="(g,index) in games" :key="index">{{g}}</li>
</ol>
</template>
</Category>

<Category title="游戏">
<template slot-scope="{games}">
<h4 v-for="(g,index) in games" :key="index">{{g}}</h4>

</template>


</Category>


</div>

</template>

<script>
import Category from './components/Category.vue'
export default {
name: 'App',
components: {
Category
}


}
</script>

<style>
.app,
.foot {
display: flex;
justify-content: space-around;

}

.app img {
width: 200px;
height: auto;
}

.fff a {
margin-left: 30px;
}

.fff h4 {
text-align: center;
}
</style>

Category.vue

<template>
<div class="container">
<h3>{{title}}分类</h3>
<slot :games="games">我是默认类容</slot>
<slot>

</slot>

</div>
</template>

<script>
export default {
name: 'Cateory',
props: ['title'],
data() {
return {

games: ['海绵宝宝', '宝宝巴士', '找你妹', 'LOL']

}
}


}
</script>

<style>
.container {
background-color: skyblue;
width: 200px;
height: 300px;
}

h3 {
text-align: center;
background-color: orange;
}
</style>