App.vue
<template>
<div style="width:250px;">
<!-- 注册自定义事件@active -->
<TitleMenu :isActive="select" @active="select= true">
<template v-slot:title>
<!-- 给具名插槽传递内容 -->
发现插槽
</template>
<template v-slot:icon>></template>
</TitleMenu>
</div>
</template>
<script>
import TitleMenu from "./components/TitleMenu"
export default {
components:{
TitleMenu,
},
data(){
return {
select:false,
}
},
}
</script>
Item.vue
<template>
<div class="item" :class="{active:isActive}" @click="handleClick">
<!-- @click,给元素注册点击事件,此处表示点击的时候运行函数handleClick -->
<!-- 插槽 -->
<slot></slot>
</div>
</template>
<script>
export default {
props:{
isActive:{
type:Boolean,
default:false,
}
},
methods:{
handleClick(){
this.$emit("active",123);
},
}
};
</script>
<style scoped>
.active{
background: #e7e7e7;
}
.item {
cursor: pointer;
width: 100%;
height: 100%;
transition:0.2s;
}
.item:hover {
background: #f4f4f4;
}
</style>
TitleMenu.vue
<template>
<div class="title-menu">
<Item :isActive="isActive" @active="$emit('active')">
<div class="inner">
<div class="left">
<slot name="title"></slot>
</div>
<div class="right">
<slot name="icon"></slot>
</div>
</div>
</Item>
</div>
</template>
<script>
import Item from "./Item"
export default {
components:{
Item,
},
props:{
isActive:{
type:Boolean,
default:false,
}
},
}
</script>
<style scoped>
.title-menu {
width: 100%;
height: 46px;
line-height: 46px;
}
.inner{
padding: 0 20px;
}
.left{
float: left;
color:#212121;
font-weight: 500;
}
.right{
float:right;
font-size: 12px;
color:#999;
}
</style>
父组件向子组件传数据props,子组件向父组件传事件event($emit