全局事件总线
vue2 : main.js
new Vue({
el:'#app',
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this // 安装全局事件总线
}
vue3
createApp(App).mount('#app')
插槽
作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件===>子组件。
1.默认插槽
App.vue
<template>
<div class="container">
<Category title="食物" :dataList="foods">
<img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="" />
</Category>
<Category title="游戏" :dataList="games"></Category>
<Category title="电影" :dataList="films">
<video
controls
src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
></video>
</Category>
</div>
</template>
Category.vue
<template>
<div class="dataList">
<h3>{{ title }}分类</h3>
<slot>
<ul>
<li v-for="item in dataList">{{ item }}</li>
</ul>
</slot>
</div>
</template>
-
如果
Category
组件标签之间有内容,显示在slot
标签的位置 -
没有内容,则显示
slot
标签内的内容
2.具名插槽
当有多个插槽时,使用具名插槽插到指定位置
App.vue
<template>
<div class="container">
<Category title="食物" :dataList="foods">
<img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt=""/>
<a slot="footer" href="https://www.felikschen.xyz" target="blank">我的主页</a>
</Category>
<Category title="游戏" :dataList="games">
<div slot="footer" class="linkList">
<a href="##">11111111</a>
<a href="##">22222222</a>
</div>
</Category>
<Category title="电影" :dataList="films">
<video slot="center" controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
<!--新语法v-slot-->
<template v-slot:footer>
<div class="linkList">
<a href="##">333</a>
<a href="##">444</a>
<a href="##">555</a>
</div>
<h3>欢迎光临</h3>
</template>
</Category>
</div>
</template>
当有多个插槽时,使用slot=“xxx”,新语法v-slot:xxx仅能用在template
标签上
Category.vue
<template>
<div class="dataList">
<h3>{{ title }}分类</h3>
<slot name="center">
<ul>
<li v-for="item in dataList">{{ item }}</li>
</ul>
</slot>
<slot name="footer"> </slot>
</div>
</template>
结果
3.作用域插槽
数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中
但使用数据所遍历出来的结构由App组件决定)
父组件App.vue
<template>
<div class="container">
<Category title="游戏">
<template scope="feliks">
<ul>
<li v-for="(g, index) in feliks.games" :key="index">{{ g }}</li>
</ul>
</template>
</Category>
<Category title="游戏">
<template scope="{games}">
<ol>
<li 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>
子组件Category.vue
<template>
<div class="dataList">
<h3>{{ title }}分类</h3>
<slot :games="games">无数据时我出来</slot>
</div>
</template>
<script>
export default {
name: "Category",
props: ["title"],
//数据在子组件自身
data() {
return {
games: ["王者荣耀", "英雄联盟", "绝地求生", "刺激战场"],
};
},
};
</script>